HTML5 - Web Sockets
By @islamzatary
By @islamzatary
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.
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).
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).
Advantages of WebSocket:
1. Not HTTP request.
2. Delivers Full Duplex Communication Model for the Web.
3. Increased Client and Server Communication Efficiency.
The WebSocket Protocol
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.
The WebSocket Protocol
If the server understands the WebSocket protocol, it agrees to the protocol switch through the Upgrade header.
WebSocket Events:
1. open.
2. message.
3. error.
4. close.
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
Example:
Echo
Resources:
Simple Chat with Node JS(Video).
About WebSocket.
WebSocket vs others.
Simple Chat with PHP.
Advantages of websockets.
Websocket vs others(stackoverflow).
by @islamzatary