Web is completely dependent on client-server connections. The client asks for requests and server responds to these requests with a response. This request-response paradigm is very commonly used and they carry the overhead of HTTP, which doesn’t make them well suited for low latency applications. Till the user has not made any action like clicking the button or triggering the API call, nothing will happen. But for low latency applications like a real time game of a chatbot this is very expensive to carry forward.
For this we have these web sockets that defines an API establishing “socket” connections between a web browser and a server. In plain words: There is a persistent connection between the client and the server and both parties can start sending data at any time.
The steps:
Open a web socket connection
var connection = new WebSocket('ws://yoursite.com', ['soap', 'xmpp']);
This is the way a new web socket connection is open that is ready to take new connections. ws or wss can be used which is similar to http and https, for secure.
SOAP is a communication protocol designed to communicate via Internet. SOAP can extend HTTP for XML messaging. SOAP provides data transport for Web services. SOAP can exchange complete documents or call a remote procedure.
Pinging to the server
// When the connection is open, send some data to the server
connection.onopen = function () {
connection.send('Ping'); // Send the message 'Ping' to the server
};
Logging the error
// Log errors
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
Communicating with server
// Sending String
connection.send('your message');
// Sending canvas ImageData as ArrayBuffer
var img = canvas_context.getImageData(0, 0, 400, 320);
var binary = new Uint8Array(img.data.length);
for (var i = 0; i < img.data.length; i++) {
binary[i] = img.data[i];
}
connection.send(binary.buffer);
// Sending file as Blob
var file = document.querySelector('input[type="file"]').files[0];
connection.send(file);
Determining accepted extensions
// Determining accepted extensions
console.log(connection.extensions);
WebSocket enables communication between parties on any domain. The server decides whether to make its service available to all clients or only those that reside on a set of well defined domains.

Leave a comment