Server Push and Server Sockets
From: http://www.xulplanet.com/tutorials/mozsdk/serverpush.php
This section will describe how to send data to mozilla from other sources.
Server Push
The Term 'Server Push' generally Means That A Server Pushes Content To The Browser Client. In Reality, A Browser Doesn't Allow this Directly. However, It May Be Emulated in A Number of Ways.
The client polls the server at a certain interval, say every five minutes. This technique is typically used to update news information. The client does this by reloading a page every so often. The client uses the 'multipart / x-mixed-replace' content type when sending a response. The content type is expected to send a series of documents one after the other, where each one will replace the previous one. The server might delay between each part, which gives the illusion that the data is being updated after an interval. This technique requires a connection to stay open. In Mozilla 1.6 and later, server sockets may be used to listen for incoming connections. This technique works similarly to the way a server would listen to connections from a browser and does not Require a connection to be kept open. However, Server Sockets May Only BE Used from Privileged Code.
All three techniques may be used in Mozilla. The first technique is fairly simple and is described in a number of places that discuss web page development. Just use a meta-tag refresh or load data using the XMLHttpRequest object. The second technique listed above has BEEN IMPROVED in Mozilla 1.7 To Work with The XmlhttpRequest Object, AS Well As with Normal Browser Page Loads. This Additional Feature Is Described Below, as it is more unique to mozilla.
Using multipart / x-mixed-replaceWhen the XMLHttpRequest object is used with the content type 'multipart / x-mixed-replace', the server can send a series of XML documents which are intended to replace each other. That means that when each new document arrives, the load listener will fire again with a new document. What you do with the new document is application-specific, but you might use it to update the user interface. Note that when a new document arrives, the old one doesn ' T Go Away if You Still Have A Reference To It. However, You Will Not Be Able To Access The Old Document THROUGH The XMLHttpRequest Object; Instead It Will Provide Access To The New Document.
You can create and retrieve a multipart remote URL in a similar way as with other URLs, however you will need to set the multipart property so that the XMLHttpRequest object knows to expect a multipart response.
Function HandleContent (Event)
{
Var Result = event.target.responsexml;
}
Var xrequest = new xmlhttpRequest ();
XRequest.multipart = true;
XRequest.open ("get", "http://www.xulplanet.com/ndeakin/tests/multipart.php", false);
XRequest.onload = handlecontent;
XRequest.send (null);
In this example, we request the URL 'http://www.xulplanet.com/ndeakin/tests/multipart.php'. The multipart property must be set to true for multipart responses. Since each part will arrive in sequence with possibly a delay in-between, in does not make sense to read the content synchronously. in fact, an error will occur if you try to. Instead, the data must be handled asynchronously and a callback registered to handle each part when it arrives. This callback is specified using the onload property. Finally, we send the request. It is important to set the properties and call the methods in the right sequence. The multipart property must be set before the call to the open method.The load listener, handleContent will be called each time a new part arrives. In this function, you would read the data and store it or update the user interface. After returning from this function, the load listener may be called again when the next part is available. Notice that The Xmlhttprequest Object Is The TA .
On the server side, you will need to ensure that the content gets sent using the content type 'multipart / x-mixed-replace' and that the content is sent in multiple parts. The details of this is beyond the scope of this document but Here Is A Simple Script in PHP Which Sends Two Xml Documents.
PHP
Header ('Content-Type: Multipart / X-Mixed-Replace; Boundary = "RN9012");
Print "--RN9012 / N";
Print "Content-Type: Application / XML / N / N";
PRINT " XML Version = '1.0'?> / n";
Print "
Print "--RN9012 / N";
Flush ();
Sleep (5);
Print "Content-Type: Application / XML / N / N";
PRINT " XML Version = '1.0'?> / n";
Print "
Print "--RN9012 - / N";
?>
Each part is separated by the string 'rn9012', which is a random string specified in the boundary in the header. It does not matter what the string is as long as it does not occur in the content anywhere. The end is signalled with two hyphens after the random string. Once this point is reached, there are no more parts, and the connection closes. In-between the two parts, we flush the output and wait for five seconds before sending the next part. Make sure to Flush the output or the script will not send the content number.
Server Sockets
A server socket is a listener which listens for incoming socket connections. The socket will listen on a specific port and respond when a message is sent to that port. The incoming messages may be from the same machine or another machine. Once you have received an Input Message, you can read it and output a response. this is the Same method Used by Web Servers When The Receive Requests for Web Pages from browsers.
Socket communication is intended to be lower level than, for example, HTTP. When using sockets, you will have to interpret and handle the data directly. The use of server sockets requires privileged code and you can not use them in unprivileged web pages.
The server socket, once created, will call a listener whenever a socket connection is made on the desired port. The listener will respond by reading the incoming data and will then output a response. If another connection is made, the listener will be called again . This will continue until the server socket is closed.Server sockets listen on a specific port which is identified by a number. you can usually use any port number you wish, assuming it is not already being used for something else. In addition, port numbers less than 1024 are usually only usable by an administrator process of the machine. you can still send data over these lower numbers, but you will not be able to listen to them, unless the machine is configured to allow such access. In The Examples Below, WE WILL Use The Port Number 7055.
Creating a Server Socket IS Fairly Simple. We use the nsiserversocket interface, as shown Below:
Var Serversocket = Components.Classes ["@ mozilla.org/network/server-socket ;1"]
.createInstance (Components.Interfaces.nsiserversocket);
Serversocket.init (7055, False, -1);
Serversocket.asynclisten (Listener);
Two methods are needed to start the server socket. The init method is used to initialize the server socket. This method takes three arguments. The first argument is the port to listen to. When a connection is made using this port, the server socket will respond. The server socket will not connect on requests through other ports. The second argument indicates whether connections are allowed from any machine or just the same machine. If this is false, any user anywhere in the world may make a connection through this server socket . If this argument is true, connections may only be made by the same machine as the server socket. If you are using C , you may also use the initWithAddress method to specify a specific IP address. Finally, the third argument to the init method specifies the length of the queue of incoming connections. The socket will only process one at a time. If more connections arrive above this queue size, they will be ignored. You will usually just use -1 for this argument to use a suitable default value.The asyncListen method is used to start the socket listening for connections. It is passed a listener object which we'll define in a moment. When a connection arrives, the listener will be called. To stop the listening Call The Server Socket's Close Method. Closing The Server Socket Does Not Stop Connections That Have Already Been Made, IT Just Prevents Any New Connections.
Serversocket.close ();
The Listener Implements The NSIServersocketListener Interface. This Interface Has Two Methods. A Simple Example Is Shown Below:
Var Listener =
{
OnSocketAccepted: Function (Serversocket, Transport)
{
Var stream = Transport.OpenOutputStream (0,0,0);
Stream.write ("OK", 2);
stream.close ();},
OnStoplistening: function (serversocket, status) {}
}
The onSocketAccepted method will be called whenever a new connection is made That means that if three connections are made, this method will be called three times They will be called in sequence;... Not all at the same time This method takes two arguments, the server socket and the socket transport. The socket transport is the incoming connection and is described in the previous section. While the first argument to the onSocketAccepted method, the server socket, will be the same for every connection, the transport will be unique to ..............................
In the example above, we open the transport's output stream using the openOutputStream and then write to it using the write method We also make sure to close the stream when we are done by using the close method This example is very simple -.. It just outputs 'OK' and closes the stream. In reality, we would want to open the input stream first, read the data sent from the client and output a response based on the input. This process is fairly similar to the example from the previous ..................
The listener also has a onStopListening method which will be called when the server socket is closed for whatever reason. The listener may use this opportunity to perform some clean up. The socket may be closed for a number of reasons, for instance if the client closed THE Connection, or if An error ocured. The reference as the status argument to onstoplistening method. this value will be an error code .here is a completion example:
Var serversocket;
Function start ()
{
Var Listener =
{
OnsocketAccepted: Function (socket, transport)
{
Try {
Var outputString = "http / 1.1 200 ok / n"
"Content-Type: Text / PLAIN / N / N"
"Hello there" transport.host "/ n";
Var stream = Transport.OpenOutputStream (0,0,0);
Stream.write (OutputString, OutputString.Length);
stream.close ();
} catch (ex2) {dump ("::" em2);}
}
OnStoplistening: function (socket, status) {}
}
Try {
Serversocket = components.classes ["@ mozilla.org/network/server-socket ;1"]
.createInstance (Components.Interfaces.nsiserversocket);
Serversocket.init (7055, False, -1);
Serversocket.asynclisten (Listener);
} catch (ex) {dump (ex);}
Document.getElementByid ("status"). Value = "start";
}
Function Stop ()
{
IF (Serversocket) serversocket.close ();
Document.getlementByid ("status"). Value = "stopped";
}
script>
hbox>