WebSocket
is a protocol providing full-duplex communications channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C.
WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application. The WebSocket Protocol is an independent TCP-based protocol. Its only relationship to HTTP is that its handshake is interpreted by HTTP servers as an Upgrade request. The WebSocket protocol makes more interaction between a browser and a web site possible, facilitating live content and the creation of real-time games. This is made possible by providing a standardized way for the server to send content to the browser without being solicited by the client, and allowing for messages to be passed back and forth while keeping the connection open. In this way a two-way (bi-directional) ongoing conversation can take place between a browser and the server. A similar effect has been achieved in non-standardized ways using stop-gap technologies such as Comet.
In addition, the communications are done over TCP port number 80, which is of benefit for those environments which block non-web Internet connections using a firewall. The WebSocket protocol is currently supported in most major browsers including Google Chrome, Internet Explorer, Firefox, Safari and Opera. WebSocket also requires web applications on the server to support it.
Web Sockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.
Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler.
Following is the API which creates a new WebSocket object.
Here first argument, url, specifies the URL to which to connect. The
second attribute, protocol is optional, and if present, specifies a
sub-protocol that the server must support for the connection to be
successful.
This will start the server listening at port 9998 and use the
handlers directory specified by the -w option where our echo_wsh.py
resides.
Now using Chrome browser open the html file your created in the beginning. If your browser supports WebSocket(), then you would get alert indicating that your browser supports WebSocket and finally when you click on "Run WebSocket" you would get Goodbye message sent by the server script.
Attaching some event handlers immediately to the connection allows you to know when the connection is opened, received incoming messages, or there is an error.
The second argument accepts optional subprotocols. It can be a string or an array of strings. Each string should represent a subprotocol name and server accepts only one of passed subprotocols in the array. Accepted subprotocol can be determined by accessing
The subprotocol names must be one of registered subprotocol names in IANA registry.
WebSocket can also receive binary messages in the latest spec. Binary frames can be received in
is a protocol providing full-duplex communications channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C.
WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application. The WebSocket Protocol is an independent TCP-based protocol. Its only relationship to HTTP is that its handshake is interpreted by HTTP servers as an Upgrade request. The WebSocket protocol makes more interaction between a browser and a web site possible, facilitating live content and the creation of real-time games. This is made possible by providing a standardized way for the server to send content to the browser without being solicited by the client, and allowing for messages to be passed back and forth while keeping the connection open. In this way a two-way (bi-directional) ongoing conversation can take place between a browser and the server. A similar effect has been achieved in non-standardized ways using stop-gap technologies such as Comet.
In addition, the communications are done over TCP port number 80, which is of benefit for those environments which block non-web Internet connections using a firewall. The WebSocket protocol is currently supported in most major browsers including Google Chrome, Internet Explorer, Firefox, Safari and Opera. WebSocket also requires web applications on the server to support it.
Web Sockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.
Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler.
Following is the API which creates a new WebSocket object.
var Socket = new WebSocket(url, [protocal] ); |
WebSocket Attributes:
Following are the attribute of WebSocket object. Assuming we created Socket object as mentioned above:Attribute | Description |
---|---|
Socket.readyState | The readonly attribute readyState represents the state of the connection. It can have the following values:
|
Socket.bufferedAmount | The readonly attribute bufferedAmount represents the number of bytes of UTF-8 text that have been queued using send() method. |
WebSocket Events:
Following are the events associated with WebSocket object. Assuming we created Socket object as mentioned above:Event | Event Handler | Description |
---|---|---|
open | Socket.onopen | This event occurs when socket connection is established. |
message | Socket.onmessage | This event occurs when client receives data from server. |
error | Socket.onerror | This event occurs when there is any error in communication. |
close | Socket.onclose | This event occurs when connection is closed. |
WebSocket Methods:
Following are the methods associated with WebSocket object. Assuming we created Socket object as mentioned above:Method | Description |
---|---|
Socket.send() | The send(data) method transmits data using the connection. |
Socket.close() | The close() method would be used to terminate any existing connection. |
WebSocket Example:
A WebSocket is a standard bidirectional TCP socket between the client and the server. The socket starts out as a HTTP connection and then "Upgrades" to a TCP socket after a HTTP handshake. After the handshake, either side can send data.Client Side HTML & JavaScript Code:
At the time of writing this tutorial, there are only few web browsers supporting WebSocket() interface. You can try following example with latest version of Chrome, Mozilla, Opera and Safari.<!DOCTYPE HTML> <html> <head> <script type="text/javascript"> function WebSocketTest() { if ("WebSocket" in window) { alert("WebSocket is supported by your Browser!"); // Let us open a web socket var ws = new WebSocket("ws://localhost:9998/echo"); ws.onopen = function() { // Web Socket is connected, send data using send() ws.send("Message to send"); alert("Message is sent..."); }; ws.onmessage = function (evt) { var received_msg = evt.data; alert("Message is received..."); }; ws.onclose = function() { // websocket is closed. alert("Connection is closed..."); }; } else { // The browser doesn't support WebSocket alert("WebSocket NOT supported by your Browser!"); } } </script> </head> <body> <div id="sse"> <a href="javascript:WebSocketTest()">Run WebSocket</a> </div> </body> </html> |
Install pywebsocket:
Before you test above client program, you need a server which supports WebSocket. Download mod_pywebsocket-x.x.x.tar.gz from pywebsocket which aims to provide a Web Socket extension for Apache HTTP Server ans install it following these steps.- Unzip and untar the downloaded file.
- Go inside pywebsocket-x.x.x/src/ directory.
- $python setup.py build
- $sudo python setup.py install
- Then read document by:
- $pydoc mod_pywebsocket
Start the Server
Go to the pywebsocket-x.x.x/src/mod_pywebsocket folder and run the following command:$sudo python standalone.py -p 9998 -w ../example/ |
Now using Chrome browser open the html file your created in the beginning. If your browser supports WebSocket(), then you would get alert indicating that your browser supports WebSocket and finally when you click on "Run WebSocket" you would get Goodbye message sent by the server script.
Getting Started
You open up a WebSocket connection simply by calling the WebSocket constructor:var connection = new WebSocket('ws://html5rocks.websocket.org/echo', ['soap', 'xmpp']);Notice the
ws:
. This is the new URL schema for WebSocket connections. There is also
wss:
for secure WebSocket connection the same way https:
is used for secure HTTP
connections.Attaching some event handlers immediately to the connection allows you to know when the connection is opened, received incoming messages, or there is an error.
The second argument accepts optional subprotocols. It can be a string or an array of strings. Each string should represent a subprotocol name and server accepts only one of passed subprotocols in the array. Accepted subprotocol can be determined by accessing
protocol
property of WebSocket object.The subprotocol names must be one of registered subprotocol names in IANA registry.
// When the connection is open, send some data to the server connection.onopen = function () { connection.send('Ping'); // Send the message 'Ping' to the server }; // Log errors connection.onerror = function (error) { console.log('WebSocket Error ' + error); }; // Log messages from the server connection.onmessage = function (e) { console.log('Server: ' + e.data); };
Communicating with the Server
As soon as we have a connection to the server (when theopen
event is fired) we can start sending data to the server using the send('your message')
method on the connection object. It used to support only strings, but
in the latest spec it now can send binary messages too. To send binary
data, you can use either Blob
or ArrayBuffer
object.// Sending String connection.send('your message'); // Sending canvas ImageData as ArrayBuffer var img = canvas_context.getImageData(0, 0, 400, 320); var binary = new Uint8Array(img.data.length); for (var i = 0; i < img.data.length; i++) { binary[i] = img.data[i]; } connection.send(binary.buffer); // Sending file as Blob var file = document.querySelector('input[type="file"]').files[0]; connection.send(file);Equally the server might send us messages at any time. Whenever this happens the
onmessage
callback fires. The callback receives an event object and the actual message is accessible via the data
property.WebSocket can also receive binary messages in the latest spec. Binary frames can be received in
Blob
or ArrayBuffer
format. To specify the format of the received binary, set the
binaryType property of WebSocket object to either 'blob' or
'arraybuffer'. The default format is 'blob'. (You don't have to align
binaryType param on sending.)// Setting binaryType to accept received binary as either 'blob' or 'arraybuffer' connection.binaryType = 'arraybuffer'; connection.onmessage = function(e) { console.log(e.data.byteLength); // ArrayBuffer object if binary };Another newly added feature of WebSocket is extensions. Using extensions, it will be possible to send frames compressed, multiplexed, etc. You can find server accepted extensions by examining the extensions property of the WebSocket object after the open event.
// Determining accepted extensions console.log(connection.extensions);
No comments:
Post a Comment