An Introduction To WebSocket

— My first hackathon

Almost a month ago, I attended remote music hackathon and were able to contribute to a real time music chat app TuneChat implementing with my teammate Raq Robinson, which pique my curiosity about webSocket.

What is webSocket?

WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. Previous methods for simulating full-duplex connections were based on polling, a synchronous method where the client makes a request to the server to see if there is any information available. The client receives a response from the server even if there is no information available. Polling works well for cases where the exact interval of message availability is known. However, in most real-time applications, message frequency is often unpredictable.

Enter WebSocket!

It allows us to have bidirectional communication and offers an open door between client and server without refreshing.

Why do we need webSocket?

For chat, collaborative document editing, stock trading applications, and multiplayer online games etc., we need to have real time immediate interaction. WebSocket are useful for real-time applications where data shown in client is changing constantly.

With WebSocket, your HTTP request becomes a single request to open a WebSocket connection and reuses the same connection between client and server. WebSocket reduces latency. For example, unlike polling, WebSocket makes a single request. The server does not need to wait for a request from the client. Similarly, the client can send messages to the server at any time. This single request greatly reduces latency over polling, which sends a request at intervals, regardless of whether messages are available. WebSocket makes real-time communication much more efficient. You can always use polling (and sometimes even streaming) over HTTP to receive notifications over HTTP. However, WebSocket saves bandwidth, CPU power, and latency. It is an innovation in performance. WebSocket is an underlying network protocol that enables you to build other standard protocols on top of it. WebSocket is part of an effort to provide advanced capabilities to HTML5 applications in order to compete with other platforms. It is all about simplicity.

How do we use webSocket?

The WebSocket object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.

First, we need to create a webSocket connection. To connect to a remote host, create a new webSocket object instance and provide the new object with the url of the target endpoint. Once established, webSocket messages can be sent back and forth using the methods defined by the WebSocket interface.

To create a connection, call Javascript’s WebSocket constructor, which returns the connection instance object. You can then listen for events on that object. These events are triggered when the connection opens or closes, messages arrive, or errors occur. You can interact with the WebSocket instance to send messages or close the connection.

The WebSocket constructor takes one required argument: the URL to which we want to connect. There is one optional argument that specifies a protocol.

// Connecting to the server on the given url
ws = new WebSocket('ws://localhost:8080');

WebSocket Event

Open: The server responds to the WebSocket connection request. It indicates that the handshake has taken place and the connection is established. The callback to the open event is called onopen.

// Event handler for connection opened event
ws.onopen = function(message) {
// Send a text message back to server
ws.send('This is a message sent from browser to server using WebSocket.');

Message: The client receives data from the server. WebSocket messages contain the data from the server. The callback for the message event is onmessage.

// Event handler for receiving text messages
ws.onmessage = function(message) {
console.log('Message received', message);

Error: There is any error in communication. The corresponding callback to the error event is onerror.

// Event handler for errors in the WebSocket object
ws.onerror = function(e) {
console.log(‘WebSocket Error:’ , e);

Close: The connection is closed. The corresponding callback to the close event is onclose.

// Event handler for connection closed event
ws.onclose = function(message) {
console.log(‘Connection closed’, e);

WebSocket Methods

send(): The socket.send(data) method transmits data using the connection. If for some reasons the connection is not available or the connection is closed, it throws an exception about the invalid connection state.

// Send a message to the server/client
ws.send('This is a message sent from browser to server using WebSockets.');

close(): The socket.close() method is used to terminate any existing connection. If the connection is already closed, then the method has no effect. The close() method has two optional arguments: code (a numerical status code) and reason (a text string).

// Ask server to close the WebSocket connection
ws.close(1000, 'Closing Connection Normally');

Written by

Multi-human-lingual and multi-programming-lingual |

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store