DEV Community

Sushanta Gupta
Sushanta Gupta

Posted on

How to send and receive data in Socket IO?

Socket.io is a library to abstract the WebSocket connections. According to the official website of socket io, Socket.IO is a library that enables low-latency, bidirectional and event-based communication between a client and a server.

What does it mean by event-based? We can send and receive data in Socket by using the following code block. We can send an event from the server and receive it in the client and vice-versa.

To Receive Data
socket.on("message", (hello) => {
console.log(hello); // world
});

To send Data
socket.emit("message", "hello");

In general, the code for sending and receiving data is
Receiving Data: socket.on(eventName, listenerFn)
Sending Data : socket.emit(eventName, Data)

We have to use same eventName for sending and catching data. There are some pre-defined events in Socket Io but we can also make our own custom events provided that the same event name is to be used in both client and server.

Top comments (0)