Websocket - What Are Websocket ?

Web is built all around sending request to server and getting a response back from server, unless browser won’t request an update, the state will remain same. Although. AJAX saves a lot of pages reload and make the web feel more dynamic. But, still we need to make a lot of AJAX request. Which requires either some user interaction or periodic polling to load new data from the server.

This way it creates a hefty load of requests on server for undesired reasons.

WebSocket: Bringing life to Web

WebSocket is a protocol providing full-duplex communications channels over a single TCP connection. In layman terms, there is a active connection between server and client.

It is kind of a pipe open at both ends server and client. Both can send any data and would be received at another end.

Getting Started

web_socket = new WebSocket('ws://mywebsocketwebsite.com');

Call back events

Sending Messages.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Send Message
web_socket.send('Ping');

// Sending file as Blob
var file = document.querySelector('input[type="file"]').files[0];
connection.send(file);

// When the connection is established
web_socket.onopen = function () {
  web_socket.send('Ping'); // Send the message 'Ping' to the server
};

// Log errors
web_socket.onerror = function (error) {
  console.log('WebSocket Error ' + error);
};

// Calback, for messages from the server
web_socket.onmessage = function (e) {
  console.log('Server: ' + e.data);
};

On server side we can use Ruby, Node.js, Java, Ruby, Python, C++ and all other popular frameworks and languages. In my last post how we can implement in Rails. In next few posts I will show we can build up a complete web socket based environment for chat.

Comments