By introducing a clean interface (see the list below), developers can replace technology such as long polling and "forever frames, so further reducing latency."
Background code
[Constructor (in domstring URL, optional in domstring protocol)] [Constructor (domstring URL, optional domstring protocol)]interface WebSocket {//readonly attribute domstring url;//Read-only property domstring url;// Ready stateconst unsigned short connecting = 0;const unsigned short OPEN = 1;const unsigned short CLOSED = 2;readonly attr Ibute unsigned short readystate;readonly attribute unsigned long bufferedamount; Networkingattribute function Onopen;attribute function Onmessage;attribute function Onclose;boolean Send (in domstring data); void close ();}; WebSocket implements Eventtarget; WebSocket realizes Eventtarget;
Using the WebSocket interface is not easy. Connect to an endpoint, create a new WebSocket instance, provide a URL for the new object, and represent the endpoint you want to connect to, as shown in the following example. Please note that the ws://and wss://prefixes indicate that the websocket and security presented a websocket connection, respectively.
JavaScript code
var mywebsocket = new WebSocket ("ws://www.websockets.org");
Establish a websocket connection from the HTTP protocol upgrade to the WebSockets protocol between the initial client and the server handshake. The connection itself is the WebSocket interface defined by the "OnMessage" and "send" functions.
Before you connect to an endpoint to send a message, you can use a series of event listeners to handle each phase of the connection's life cycle, as shown in the following example.
JavaScript code
Mywebsocket.onopen = function (evt) {alert ("Connection open ..."); Mywebsocket.onmessage = function (evt) {alert ("Received Message:" + evt.data);}; Mywebsocket.onclose = function (evt) {alert ("Connection closed.");
Send a message to the server, simply call "send" and provide what you want to provide. After the message is sent, it is called "close" to terminate the connection, as shown in the following example. As you can see, it's really not much easier.
JavaScript code
Mywebsocket.send ("Hello websockets!"); Mywebsocket.close ();