Buildtide
Author: Hussain Mir Ali

I am interested in web and mobile technologies.

If you have any questions or feedback then message me at devtips@Buildtide.com.

WebSocket Client with JavaScript


Fig 1.0 Components of WebSocket


Client:

'WebSocket' Object:  

The 'WebSocket' object enables developers to establish a connection with the server. The URL for the server endpoint along with specification for sub-protocols can be passed to the  WebSocket  constructor. In this case the client is a web browser.

let socketInstance = new WebSocket("ws://www.myservice.com/endpoint", ["protocolA", "protocolB"]);

The first argument passed to the constructor is the URL representing the server endpoint and the second argument can be a single argument or an array representing sub protocols for WebSocket which are optional.

Events:

onopen:
When the connection between the client and the server is created the 'open' event fires. So any communication with server can be performed in the event callback.

socketInstance.onopen = (event) => {
//start communicating with the server
};

onmessage:
The 'onmessage' event is fired when the client receives information from the server. And the information can be accessed through the event callback.

socketInstance.onmessage = (event)=> {
//do something with the data
console.log(event.data);
}

onerror:
This event gets fired when there is an error in communication between the client and the server. Developers can use this event to warn users that the web application will close.

socketInstance.onerror = (event) => {
//do something with the event data
console.log(event.data);
};

onclose:
The 'onclose' event is fired right after the 'onerror' event or when calling the 'close' method. Developers can use this event to close the application and perform any final operations before the user is redirected.

socketInstance.onclose = (event) => {
//check event code for cause
if (event.code != 1000) {
// if 1000 it means that the connection was closed normally.
// inform user if not online
if (!navigator.onLine) {
console.log("You are offline. Please connect to the Internet and try again.");
}
}
}

Methods:

Once an instance of 'WebSocket' is created then it can be used to start communicating with the server.

send:
The send method can be used to send information to the server in the form of string or JSON string. But the client can only communicate with the server after 'open' event is fired so the communication logic can be placed inside an event callback. 

socketInstance.onopen = (event)=> {

let message = {
userId: 'asdfow9238x',
score: 140,
time: 4500,
turn: 5
}

socketInstance.send(JSON.stringify(message);
};

close:

socketInstance.close();

The connection can be simply closed via the 'close' method. After the connection is closed the 'onclose' event gets fired.