Websocket beginner guide

What is WebSocket?

WebSocket provides a way to exchange data between the browser and server via a persistent connection. The data can be passed in both directions as “packets”, without breaking the connection and the need for additional HTTP requests.

 

Where can we use WebSocket?

we use WebSocket where we need real-time data sharing i.e. online trading platforms, games, and social media platforms.

 

Frontend Example –

To open a WebSocket connection we need to create a new protocol.

let socket = new WebSocket(“ws://localhost:3000”);

 

Once the socket is created, we should listen to events on it. There are totally 4 events:

open – connection established,

message – data received,

error – WebSocket error,

close – connection closed.
let socket = new WebSocket("ws://localhost.com");




socket.onopen = function(e) {

  alert("[open] Connection established");

  alert("Sending to server");

  socket.send("My name is tejendra");

};


socket.onmessage = function(event) {

  alert(`[message] Data received from server: ${event.data}`);

};




socket.onclose = function(event) {

  if (event.wasClean) {

    alert(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);

  } else {

    alert('[close] Connection died');

  }

};

 

socket.onerror = function(error) {

  alert(`[error] ${error.message}`);

};

 

We need to have a server database for the above demo too, so we can connect to the server.

So you’ll see events open → message → close. and if there is an error then onerror in the end.

When a new WebSocket (URL) is created, it starts connecting immediately.

 

During the connection, the browser (using headers) asks the server: “Do you support Websocket? ”And if the server replies “yes”, then the talk continues in WebSocket protocol.

If you want to use it in the front end, the best way to use it is socket.io which works on both the client and server sides.

There are some methods to use in socket.io

//connect to server

const socket = io("http://localhost.com");




//on() - listen to custom events or default events. (receive)

socket.on('connect', console.log('connect to server'))




//emit() - sent custom or default event to server. (send)

socket.emit('custom-event', 10, 'Hi', 'send')

 

important – both server and client have the same event name to work.

But how to send data from the server?

For that, we need to use the same methods on the server side too.

//broadcast.emit() - send custom or default event to everyone except the sender.

socket. broadcast. emit('custom event, 10, 'Hi', 'send')




//to(room) - send a message to a specific room or group

socket. to("some room").emit("some event");

Leave a Reply