<< Back to the blog

HTML5 - Web Sockets




By @islamzatary

List of Advanced HTML5 Topics:


Web Sockets

WebSocket is as a transport layer defines an API that enables web pages to use the WebSockets protocol for two-way communication with a remote host.

WebSocket interface is defines a full-duplex communication channel that operates through a single socket over the Web.

Web Sockets

Real Time Messages
1. WebSocket (create TCP connection to server, and keep it as long as needed. Server or client can easily close it, Bidirectional communication aty any time.).
2. Ajax (creates connection to server on each request, sends request & and gets response from server, so one connection for each request).
3. long polling(creates connection to server, but keep-alive connection open for some time, during connection open client can receive data from server. clients have to reconnect after connection closed).

Web Sockets

Real Time Messages:
4. WebRTC (peer-to-peer type of transport & allows to transport data in reliable as well as unreliable ways, its used for high volume data transfer such as video/audio streaming where reliability).

Web Sockets

Advantages of WebSocket:
1. Not HTTP request.
2. Delivers Full Duplex Communication Model for the Web.
3. Increased Client and Server Communication Efficiency.

Web Sockets

The WebSocket Protocol
WebSocket Request
The browser sends a request to the server, indicating that it wants to switch protocols from HTTP to WebSocket. The client expresses its desire through the Upgrade header.

Web Sockets

The WebSocket Protocol WebSocket Response
If the server understands the WebSocket protocol, it agrees to the protocol switch through the Upgrade header.

Web Sockets.

WebSocket Events:
1. open.
2. message.
3. error.
4. close.

Web Sockets.

Using the HTML5 WebSocket API
var myWebSocket = new WebSocket("ws://www.websockets.org");
myWebSocket.onopen = function(evt) { alert("Connection open ..."); };
myWebSocket.onmessage = function(evt) { alert( "Received Message: " + evt.data); };
myWebSocket.onclose = function(evt) { alert("Connection closed."); };

myWebSocket.send("Hello WebSockets!");
myWebSocket.close();

JSbin demo

Web Sockets

Example:
Echo

Web Sockets.

Resources:
Simple Chat with Node JS(Video).
About WebSocket.
WebSocket vs others.
Simple Chat with PHP.
Advantages of websockets.
Websocket vs others(stackoverflow).

Web Sockets




Wrapping up








<< Back to the blog

by @islamzatary