By introducing a concise interface (see the list below), developers can replace technologies such as long polling and "always frame", 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 attribute DOMString URL; // ready stateconst unsigned short CONNECTING = 0; const unsigned short OPEN = 1; const unsigned short CLOSED = 2; readonly attribute 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 implements EventTarget;
Using the WebSocket interface is not simple. Connect to an endpoint and create a new WebSocket instance to provide a URL for the new object, representing the endpoint you want to connect to, as shown in the following example. Note that the ws: // and wss: // prefixes indicate that WebSocket and Security propose WebSocket connections, respectively.
JavaScript code
var myWebSocket = new WebSocket("ws://www.websockets.org");
Establish a WebSocket connection from the HTTP protocol to the WebSockets protocol handshake between the initial client and the server. The connection itself is a WebSocket interface defined by the onmessage and send functions.
Before you connect to an endpoint to send a message, you can process a series of event listeners for each stage of the connection lifecycle, 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."); };
To send a message to the server, you only need to call "send" and provide the content you want to provide. After a message is sent, it is called "approaching" to terminate the connection, as shown in the following example. As you can see, it cannot be easier.
JavaScript code
myWebSocket.send("Hello WebSockets!"); myWebSocket.close();