DEV Community

Tejendra Singh Rajawat
Tejendra Singh Rajawat

Posted on

Beginner guide to websocket

Q. What is websocket ?
A. websocket provides a way to exchange data between browser and server via a persistent connection. The data can be passed in both directions as “packets”, without breaking the connection and the need of additional HTTP-requests.

Q. where can we use websocket ?
A. we use websocket where we need realtime data sharing i.e. online trading platform, games and social media platforms.

Frontend Example -
To open a websocket connection we need to create new protocol.

let socket = new WebSocket("ws://localhost:3000");
Enter fullscreen mode Exit fullscreen mode

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}`);
};
Enter fullscreen mode Exit fullscreen mode

We need to have server database for above demo too, so we can connect to server.
So you’ll see events open → message → close. and if there is error then onerror in end.

When 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 frontend so the best way to use is socket.io which works on both client and server side .

There are some methods to use in socket.io

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

//on() - listen to custom event or default event. (receive)
socket.on('connect', console.log('connect to server'))

//emit() - sent custom or default event to server. (send)
socket.emit('costum-event', 10, 'Hi', 'send')
Enter fullscreen mode Exit fullscreen mode

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

But how to send data from server ?
For that we need to use same methods in server side too.

//broadcast.emit() - send custom or default event to everyone except the sender.
socket.broadcast.emit('costum-event', 10, 'Hi', 'send')

//to(room) - send message to a specific room or group
socket.to("some room").emit("some event");
Enter fullscreen mode Exit fullscreen mode

Top comments (0)