473,893 Members | 1,890 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can server interrupt client in browser?

I have a Javascript program which runs in the browser and has
functions work(), and stop().
It listens to commands from the server to work() and can be
interrupted by the server to stop().
I am using XmlHttpRequest to talk to the server.
So I use http GET to send a command "ready" to the server, which
replies at some point in time by sending "work" which is invoked by
the callback.

As per my understanding, the browser client is single threaded. How to
get the server to interrupt the browser client to say "stop"?

I modified Flanagan's example code here:

var HTTP = {

// This is a list of XMLHttpRequest creation factory functions to try
_factories : [
function() { return new XMLHttpRequest( ); },
function() { return new ActiveXObject(" Msxml2.XMLHTTP" ); },
function() { return new ActiveXObject(" Microsoft.XMLHT TP"); }
],

// When we find a factory that works, store it here
_factory : null,

// Create and return a new XMLHttpRequest object.
//
// The first time we're called, try the list of factory functions
until
// we find one that returns a nonnull value and does not throw an
// exception. Once we find a working factory, remember it for later
use.
//
newRequest : function() {
if (HTTP._factory != null) return HTTP._factory() ;

for(var i = 0; i < HTTP._factories .length; i++) {
try {
var factory = HTTP._factories[i];
var request = factory();
if (request != null) {
HTTP._factory = factory;
return request;
}
}
catch(e) {
continue;
}
}

// If we get here, none of the factory candidates succeeded,
// so throw an exception now and for all future calls.
HTTP._factory = function() {
throw new Error("XMLHttpR equest not supported");
}
HTTP._factory() ; // Throw an error
},

/**
* Use XMLHttpRequest to fetch the contents of the specified URL
using
* an HTTP GET request. When the response arrives, pass it (as plain
* text) to the specified callback function.
*
* This function does not block and has no return value.
*/
toServer : function(url) {
var request = HTTP.newRequest ();
request.onready statechange = function() {
if (request.readyS tate == 4 && request.status == 200)
MyProxy.fromSer ver(request.res ponseText);
}
request.open("G ET", url, true); // 3rd param implies asynchronous
console.log("se nding " + url);
request.send(nu ll);
},

};

......
// MyProxy
....
fromServer: function(comman d) {
console.log("fr omServer: " + command);
eval(command);
},
thanks,
Anil
Oct 21 '08 #1
7 4698
On Oct 22, 12:49*am, Anil <anil.r...@gmai l.comwrote:
As per my understanding, the browser client is single threaded. How to
get the server to interrupt the browser client to say "stop"?
The communication has to be initiated by the client. Either keep
polling the server periodically[Ajax with polling] or use something
along the lines of Comet technology [Web Server push enabled by the
use of long held http connections].
<URL: http://en.wikipedia.or g/wiki/Comet_(programm ing)>

/sasuke

Oct 22 '08 #2
On Oct 21, 10:46 pm, sasuke <database...@gm ail.comwrote:
On Oct 22, 12:49 am, Anil <anil.r...@gmai l.comwrote:
As per my understanding, the browser client is single threaded. How to
get the server to interrupt the browser client to say "stop"?

The communication has to be initiated by the client. Either keep
polling the server periodically[Ajax with polling] or use something
along the lines of Comet technology [Web Server push enabled by the
use of long held http connections].
<URL:http://en.wikipedia.or g/wiki/Comet_(programm ing)>

/sasuke
Thanks for replying. I was wondering if a trick like this would work,
but it doesn't seem to. Is it a bug in my implementation or is it
conceptually faulty?
In MyProxy.fromSer ver(), issue another toServer("url") .
Thus there will always be a GET request pending. Since it is
asynchronous, it will return immediately. But the callback will occur
while the client is executing.
so what happens here - what will the browser do - will it simply
block, or a new thread be created? My understanding is stuck here.
Oct 22 '08 #3
On Oct 22, 7:20 pm, Anil <anil.r...@gmai l.comwrote:
On Oct 21, 10:46 pm, sasuke <database...@gm ail.comwrote:
On Oct 22, 12:49 am, Anil <anil.r...@gmai l.comwrote:
As per my understanding, the browser client is single threaded. How to
get the server to interrupt the browser client to say "stop"?
The communication has to be initiated by the client. Either keep
polling the server periodically[Ajax with polling] or use something
along the lines of Comet technology [Web Server push enabled by the
use of long held http connections].
<URL:http://en.wikipedia.or g/wiki/Comet_(programm ing)>
/sasuke

Thanks for replying. I was wondering if a trick like this would work,
but it doesn't seem to. Is it a bug in my implementation or is it
conceptually faulty?
In MyProxy.fromSer ver(), issue another toServer("url") .
Thus there will always be a GET request pending. Since it is
asynchronous, it will return immediately. But the callback will occur
while the client is executing.
so what happens here - what will the browser do - will it simply
block, or a new thread be created? My understanding is stuck here.
Javascript implementations don't support threading. When making asyn
requests, the browser never blocks; instead as soon as a response is
returned from the server, the callback function is executed which
performs the required processing.

Like I mentioned before, just keep polling the server for commands
using setInterval and make provision for a NO-OP command. Thoroughly
read the Comet article in case you want to avoid polling. Modern web
servers like Tomcat come with in-built Comet support.

/sasuke
Oct 22 '08 #4
Anil wrote:
I have a Javascript program which runs in the browser and has
functions work(), and stop().
It listens to commands from the server to work() and can be
interrupted by the server to stop().
I am using XmlHttpRequest to talk to the server.
So I use http GET to send a command "ready" to the server, which
replies at some point in time by sending "work" which is invoked by
the callback.

As per my understanding, the browser client is single threaded.
That is correct, however it is rather irrelevant here because the point
in using asynchronous request-response handling (as you do) is to work
around that.
How to get the server to interrupt the browser client to say "stop"?
One possibility is the obvious:

fromServer: function(comman d) {
console.log("fr omServer: " + command);

if (command != "stop")
{
eval(command);
}
},

That is not interrupting anything, though, as nothing needs to be
interrupted in the first place.

However, the reference implementation and other implementations also support
a way to cancel the current HTTP request while it is in progress, the
abort() method:

<http://msdn.microsoft. com/en-us/library/ms760305(VS.85) .aspx>
<https://developer.mozil la.org/En/XMLHttpRequest>
<http://www.opera.com/docs/specs/xhr/index.dml>
<http://developer.kde.o rg/documentation/library/3.4-api/khtml/html/xmlhttprequest_ 8cpp-source.html>
<http://trac.webkit.org/browser/branches/Safari-3-2-branch/WebCore/xml/XMLHttpRequest. cpp#L481>
I modified Flanagan's example code here:
You should not use Flanagan's code, and particularly not this code as it is
error-prone.
PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
Oct 22 '08 #5
Can you please tell me why it is error prone? Is there better code
that will do the same thing... if so, can you please point me to it?

Also, "stop" is not for canceling the http request. stop() does a
specific task.
thanks,
Anil

On Oct 22, 3:21 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
wrote:
>
You should not use Flanagan's code, and particularly not this code as it is
error-prone.

PointedEars
Oct 24 '08 #6
Anil wrote:
Can you please tell me why it is error prone?
It uses exception handling without fallback to begin with.
Is there better code that will do the same thing...
Yes.
if so, can you please point me to it?
It is located in your /dev/brain.
Please don't top-post. Reply below parts of trimmed quotes instead.
PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
Oct 24 '08 #7
Hi Anil,
As per my understanding, the browser client is single threaded. How to
get the server to interrupt the browser client to say "stop"?
On the off-chance that you're not like every other xenophobic little-HTTPer
here, and you won't let any personal prejudices stop you from thinking
outside the Ajax-box for a moment, let me offer you a Java Applet
alternative. (If/when Flash or Silverlight get around to supporting UDP you
can probably do it with them as well.)

If you'd like to see an example of a threaded Java Applet that receives UDP
messages from an abitrary server(s), then please: -

1) Click on the following link and read the instructions:
http://manson.vistech.net/~tier3/tier3pager.html

2) Telnet to manson.vistech. net. (If you don't already have an account on
the Deathrow cluster then please use Username: DEMO Password: USER) and
then:

$set term/width=132
$run sys$users:[users.tier3.web]demo_udp_msg

3) Enter the IP address of your client node. Your "stock-monitor" from step
1 should now spring into life with random stock-prices generated at 2sec
intervals. (NATed clients will find this bit problematic :-)

4) Enter any adhoc messages that you wish to appear in the seperate Java
Frame on the client.

OPCOM messages to web-subscribers? CHAT conferences? Stock-Watching? Alarm
Monitoring? - It's all good!

The rationale here is not to use up a TCP/IP connection and a server
process/thread for ad-hoc, asynchronous, broadcasts, and most definitely do
use something other than a connectionless, context-devoid,
session-hijackable, pile of http-pooh as your middleware backbone.

Cheers Richard Maher

PS. The code for Tier3Pager.java aqnd DEMO_UDP_MSG.CO B are below, but all
can be found at SYS$USERS:[USERS.TIER3.WEB]

PPS. If this is for the Intranet then you might wish to look at Broadcast or
even Multicast functionality as well, and eliminate the "subscribe" step
altogether.

Tier3Pager.java
===========

/**
* Copyight Tier3 Software. All rights reserved.
*
* Author: Richard Maher
*
**/

import java.applet.App let;
import java.awt.*;
import java.net.*;
import java.io.IOExcep tion;
import netscape.javasc ript.JSObject;
import netscape.javasc ript.JSExceptio n;

public class Tier3Pager extends Applet
{
private String hostName;
private JSObject browser;
private static MessageThread socketThread;
private static Tier3Talk chat;

public class MessageThread extends Thread
{
private DatagramSocket socket;
private DatagramPacket packet;
private String threadData;

public MessageThread(S tring name, String txt) throws Exception
{
super(name);

byte[] buffer;
threadData = txt;

String port = getParameter("P ORT");
String maxBuf = getParameter("M AXBUF");
try
{
if (port == null)
socket = new DatagramSocket( );
else
socket = new DatagramSocket( Integer.parseIn t(port));

if (maxBuf == null)
buffer = new byte[512];
else
buffer = new byte[Integer.parseIn t(maxBuf)];

packet = new DatagramPacket( buffer, buffer.length);
}
catch (Exception e)
{
e.printStackTra ce();
System.out.prin tln("Unable to create UDP Socket");
throw new Exception("Mess age thread could not be created");
}

setDaemon(true) ;
start();
}

public void shutdown()
{
socket.close();
}

public int getLocalPort()
{
return socket.getLocal Port();
}

public void run()
{
System.out.prin tln("Started Message thread. ThreadData = "
+threadData);
String args[] = {"Started Message Thread " + threadData};
browser.call("a lert", args);
boolean stopThread = false;

readLoop:
while (!stopThread)
{
try
{
socket.receive( packet);
String received = new String(packet.g etData(),
0,packet.getLen gth());
processMessage( received);
}
catch (SocketExceptio n e)
{
System.out.prin tln("Shutting up shop");
stopThread = true;
continue readLoop;
}
catch (IOException e)
{
e.printStackTra ce();
System.out.prin tln("Unable to retrieve UDP message");
}
}

System.out.prin tln("Thread run() unit terminating");
}

public void processMessage( String msgText)
{
int msgType = Integer.parseIn t(msgText.subst ring(0,2));
switch (msgType){
case 1:
chat.append(msg Text.substring( 2));
break;
case 2:
String args[] = {msgText.substr ing(2)};
try {browser.call(" priceUpdate", args);}
catch (JSException e)
{
System.out.prin tln("Error when calling
JSpriceUpdate() ");
}
break;
default:
System.out.prin tln("Unknown rec type"+msgText);
}
}
}

public void init()
{
System.out.prin tln("Initializi ng. . .");
hostName = getCodeBase().g etHost();

chat = new Tier3Talk("Tier 3 Messages");
requestFocus();

browser = JSObject.getWin dow(this);

if (socketThread == null)
{
try
{
socketThread = new MessageThread(" MsgDaemon", "SomeData") ;
}
catch (Exception e)
{
e.printStackTra ce();
System.out.prin tln("Could not init Tier3Pager");
}
}
}

public void alert(String alertText)
{
String args[] = {alertText};
browser.call("a lert", args);
}

public void destroy()
{
if (chat != null)
chat.dispose();

boolean stillDying;

if (socketThread != null){
socketThread.sh utdown();
do
{
stillDying = false;
System.out.prin tln("Joining MessageThread") ;
try {socketThread.j oin();}
catch (InterruptedExc eption e){
System.out.prin tln("Interrupte d Join");
stillDying = true;
}
} while (stillDying);

socketThread = null;
}

System.out.prin tln("Tier3Pager Applet Rundown complete");
super.destroy() ;
}
}
"Anil" <an*******@gmai l.comwrote in message
news:ff******** *************** ***********@a70 g2000hsh.google groups.com...
I have a Javascript program which runs in the browser and has
functions work(), and stop().
It listens to commands from the server to work() and can be
interrupted by the server to stop().
I am using XmlHttpRequest to talk to the server.
So I use http GET to send a command "ready" to the server, which
replies at some point in time by sending "work" which is invoked by
the callback.

As per my understanding, the browser client is single threaded. How to
get the server to interrupt the browser client to say "stop"?

I modified Flanagan's example code here:

var HTTP = {

// This is a list of XMLHttpRequest creation factory functions to try
_factories : [
function() { return new XMLHttpRequest( ); },
function() { return new ActiveXObject(" Msxml2.XMLHTTP" ); },
function() { return new ActiveXObject(" Microsoft.XMLHT TP"); }
],

// When we find a factory that works, store it here
_factory : null,

// Create and return a new XMLHttpRequest object.
//
// The first time we're called, try the list of factory functions
until
// we find one that returns a nonnull value and does not throw an
// exception. Once we find a working factory, remember it for later
use.
//
newRequest : function() {
if (HTTP._factory != null) return HTTP._factory() ;

for(var i = 0; i < HTTP._factories .length; i++) {
try {
var factory = HTTP._factories[i];
var request = factory();
if (request != null) {
HTTP._factory = factory;
return request;
}
}
catch(e) {
continue;
}
}

// If we get here, none of the factory candidates succeeded,
// so throw an exception now and for all future calls.
HTTP._factory = function() {
throw new Error("XMLHttpR equest not supported");
}
HTTP._factory() ; // Throw an error
},

/**
* Use XMLHttpRequest to fetch the contents of the specified URL
using
* an HTTP GET request. When the response arrives, pass it (as plain
* text) to the specified callback function.
*
* This function does not block and has no return value.
*/
toServer : function(url) {
var request = HTTP.newRequest ();
request.onready statechange = function() {
if (request.readyS tate == 4 && request.status == 200)
MyProxy.fromSer ver(request.res ponseText);
}
request.open("G ET", url, true); // 3rd param implies asynchronous
console.log("se nding " + url);
request.send(nu ll);
},

};

.....
// MyProxy
...
fromServer: function(comman d) {
console.log("fr omServer: " + command);
eval(command);
},
thanks,
Anil

Nov 3 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2580
by: Matt | last post by:
I think this is the basic concept in ASP server-side development. My boss told me web application is NOT client-server application. I argued with him because browser is the client, and the server code put in server. Then web application should be a client-server application. My understanding is that a web application is an application that runs on a browser. But client-server application is not necessary a web application. Please...
12
12447
by: HarveyB | last post by:
I would like to generate non-modal popup windows from ASP.Net code-behind. I have tried using Client Side scripting like "function Test(){ window.open('test.htm',_blank, 'height=200,width=400,status=no,toolbar=no, menubar=no,location=no resizable=no scrollable=no'); but I can't seem to invoke the client side script from within a Server Side Form. I know I can use the context with to Response.redirect or Server.transfer to return a
2
3953
by: Dicky Cheng | last post by:
Hi, I am using .net remoting technology. I set up a .net remoting client and server in IIS. When the client calls the server, the server will run a long duration method (30-60seconds). I have a test on it that if the network broken at the time the client have already send the remoting request and waiting for the server, the client side will wait infinitely by default, even if i already set the executionTimeout to 90seconds in...
5
3619
by: KathyB | last post by:
If someone could just explain this to me...I just don't get it! I have an aspx page where I retrieve several session variables and use xmlDocument to transform xml file with xsl file into an instruction document (not data based) - same as using an xml web control. The resulting html is on the client? but what about the server side of things? Trying to figure out how to change and save the xmlDocument. It I put a button OUTSIDE of the...
3
11230
by: Denon | last post by:
How to trap browser close event in SERVER side? I read a lot of forum message, it talk about onclose(), onunload() and even onbeforeunload() event. However, all of theses are based on javascript written on the client browser , like IE. To send a POST to web server to acknowledge its close event. However, I just think, web server and client browser is a TCP connection. And if the client browser is close and it imply the TCP socket is...
5
4862
by: zorhel | last post by:
Hi. My clients will be IE, Mozilla and Opera in a Windows and *nix OS. So, my web app need to, from a server, send messages to a specific client (browser), send messages for all clients, redirect a client to another page. In other way, a client will be able to send messages to another client, throw the server. These are the first funcionalities.
7
3326
by: kaburke | last post by:
Is there a way to make a page at the receiving end of a Server.Transfer think that the request is a Postback? (When I say "think it is a Postback," I mean I want the page to go through the ENTIRE event sequence for a postback, including LoadViewState, ProcessPostData, etc.) Even when Sever.Transfer transfers a page to itself (i.e., Page A.aspx contains Server.Transfer("A.apsx")) the request is seen as a first-time request, not a Postback....
6
2325
by: Marc | last post by:
How could I directly trigger a very simple on localhost and a known port listening server from my internet browser client? Local host means the little server would be running on the client machine, where my browser resides. Browser would be IE, O.S. Windows 2000 or XP, and it's for an intranet application. The goal of the little server on the localhost client side would be to trigger a scanner, with the TWAIN library. Also this server is...
7
3181
by: Samuel | last post by:
Hi, I am looking for some recommendations for client/server technologies and for the communication involved. I am currently planning to port a Perl application that has grown out of proportion to another language and architecture. For this purpose, I am investigating technologies that best fit the requirements. The current plan for the architecture of the ported software includes:
0
9988
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9833
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10841
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10931
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9648
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8025
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5860
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4684
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4282
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.