Skip to content
← Back to Community
Socket.IO Tutorial - What it's for and how to use
Profile icon
ruiwenge2

Socket.IO Tutorial

Welcome to this Socket.IO tutorial, which will teach you how to use the library.

Why it's useful

Socket.IO is a JavaScript library for communication between web clients and servers in real time. It can be used to make multiplayer games. My chat project, connect 4 game, video conferencing app, and multiplayer pong game all used Socket.IO.

Content

  • Sending a message in client and server
  • Recieving a message in client and server
  • Socket IDs
  • Rooms
  • Different ways to send messages

We'll be using Express for the server. I'll be explaining a lot of the code with comments.

Sending/recieving a message in client and server

Let's start by creating a Node.js repl. Then insert the following code:

const express = require("express"); // use express const app = express(); // create instance of express const server = require("http").Server(app); // create server const io = require("socket.io")(server); // create instance of socketio app.use(express.static("public")); // use "public" directory for static files io.on("connection", socket => { socket.on("joined", () => { // when server recieves the "joined" message io.emit("joined"); // send message to client }); socket.on("disconnect", () => { // when someone closes the tab io.emit("leave"); }); }); server.listen(3000); // run server

Once you run the code, Replit will install packages. Then you'll see a page that says Cannot GET /, because we haven't added any pages yet.

Remember, you use socket.on to recieve a message, and socket.emit to send a message.

Next, create a new folder called public, and in the folder, create a file called index.html and a file called script.js.

In public/index.html add this:

<!DOCTYPE html> <html> <head></head> <body> <script src="/socket.io/socket.io.js"></script> <!-- use the library --> <script src="/script.js"></script> <!-- use "script.js" file --> </body> </html>

And in public/script.js add this code:

const socket = io(); // create new instance socket.emit("joined"); // tell server that someone opened the page socket.on("joined", () => { // when server tells client that someone has opened the page alert("someone joined"); }); socket.on("leave", () => { alert("someone left"); // when server tells client that someone has closed the page });

Now, to test it, open the website. It should show a popup saying someone joined. Then open the website again in another tab to make sure that the socket.on works in the first tab. In both tabs, it should say someone joined. When you close one of the tabs, the other tab should say someone left.

Yay! We've made a really simple multiplayer website!

But what if we wanted to pass in values, and the client that recieved the message also recieves the value? Well, lucky for us, it's super easy in Socket.IO. If we wanted to use socket.emit or io.emit to pass in a variable, you could just pass in more arguments:

socket.emit("number", 10);

or

io.emit("number", 10);

And to recieve the message, you would do:

socket.on("number", number => { // do something here });

You can add as many arguments as you would like:

// send message socket.emit("numbers", 1, 2, 3); // recieve message socket.on("numbers", (number1, number2, number3) => { // do something with the variables });

Socket IDs

A socket ID is a identifier of 20 random characters, for example 7CFGPYjHt_Qk7JMBAAAL. Socket IDs are useful if you wanted to keep track of users online, or if you wanted to send a message to just one user.

To get the ID, you would do something like this:

var id = socket.id;

If you used socket.id in the client, it would return their Socket ID. If you used socket.id in the server, it would return the Socket ID of the client that sent a message.

To send a message from the server to just one client, you would do this:

io.to("SOCKETID").emit("message", "value");

Rooms

Socket.IO rooms make it easy for you implement rooms in a website. All of my projects mentioned at the start of this tutorial had rooms.

To join a room, you would use this code in the server:

socket.join("ROOM")

And to leave a room:

socket.leave("ROOM");

To send a message to all clients in a room you would do this:

io.to("ROOM").emit("message", "value");

Let's try making our repl allow people to enter their names and join rooms.

In index.js:

const express = require("express"); // use express const app = express(); // create instance of express const server = require("http").Server(app); // create server const io = require("socket.io")(server); // create instance of socketio app.use(express.static("public")); // use "public" directory for static files const users = {}; // create dictionary of users and their socket ids io.on("connection", socket => { socket.on("joined", (username, room) => { // when server recieves the "joined" message socket.join(room); // join the room io.to(room).emit("joined", username); // tell the clients in the room that someone has joined users[socket.id] = {username:username,room:room}; // add user to dictionary console.log(users); }); socket.on("disconnect", () => { // when someone closes the tab let username = users[socket.id]["username"]; // get username of user let room = users[socket.id]["room"] // get room the user was in io.to(room).emit("leave", username); // tell the clients in the room that someone has left delete users[socket.id]; // remove user from dictionary console.log(users); }); }); server.listen(3000); // run server

In public/index.html, it's the same as before. And in
public/script.js:

const socket = io(); // create new instance const username = prompt("enter name:"); // ask for the user's name const room = prompt("enter the room:"); // ask for what room the user wants to go socket.emit("joined", username, room); // tell server the username and room of the person who joined socket.on("joined", user => { // when server tells client that someone has joined alert(user + " joined"); }); socket.on("leave", user => { // when server tells client that someone has left alert(user + " left"); });

Different ways to send messages

Here are the ways you can send a message from the server to the client:

// sending to sender only socket.emit("message", "value"); // sending to all clients, including sender io.emit("message", "value"); // sending to all clients except sender socket.broadcast.emit("message", "value"); // sending to all clients in room except sender socket.broadcast.to("ROOM").emit("message", "value"); // sending to all clients in room including sender io.to("ROOM").emit("message", "value"); // sending to sender only if they are in the room socket.to("ROOM").emit("message", "value"); // sending to individual Socket ID socket.broadcast.to("SOCKETID").emit("message", "value");

This tutorial has come to an end, and I hope you learned something!

Bye!

Voters
Profile icon
jacksonMiller0
Profile icon
Mantaray06
Profile icon
sharpoen
Profile icon
TofuToast
Profile icon
lcraft
Profile icon
arnavpatel2021
Profile icon
RyanKeeler
Profile icon
RyanTang11
Profile icon
6w6
Profile icon
themajikspoon
Comments
hotnewtop
Profile icon
RoBlockHead

What’s up with all these high quality tutorials recently on RT? Nice post!

Profile icon
ruiwenge2

@RoBlockHead thanks!

Profile icon
VulcanWM

Nice!

Profile icon
ruiwenge2

@VulcanWM thanks

Profile icon
VulcanWM
Profile icon
umair10533

What's the deal with all the high-quality tutorials that have been posted recently on RT? Very nice post! https://www.ditrc.com/cms/recruitment-agencies-for-qatar

Profile icon
CodingElf66

Nice tutorial!

Profile icon
ruiwenge2
Profile icon
Highwayman

This is awesome except for this single part:

const express = require("express"); const app = express(); const server = require("http").Server(app); const io = require("socket.io")(server);

I don't see any explanations for arguably the most important piece of code in the entire program.

Profile icon
ruiwenge2
Profile icon
Highwayman

yay! ok here's your updoot. @ruiwenge2

Profile icon
ruiwenge2

@Highwayman lol thanks

Profile icon
AnitaTurner

Thanks for sharing this tutorial!

Profile icon
ruiwenge2
Profile icon
illuminatieye

Is this like web socket?

Profile icon
justaperson22

Maybe you can explain some of the code. Otherwise it's pretty good

Profile icon
ruiwenge2

@justaperson22 i did, i explained it in the comments. they start with //

Profile icon
justaperson22

@ruiwenge2 Oh, I see.

Profile icon
JWZ6

Not Bad

Profile icon
ruiwenge2

@JWZ6 lol does that mean it's good or it's okay?

Profile icon
JWZ6

@ruiwenge2 decent

Profile icon
blahthingy

Cool

So you can make multiplayer games with socket.io?

Profile icon
ruiwenge2
Profile icon
blahthingy
Profile icon
SwiftOwl

Awesome, I learned a lot!

Profile icon
ruiwenge2

@SwiftOwl thx :)

Profile icon
LauraLi3

Thank you so much for sharing this info which really helpful to solve my issue...
retro bowl

Profile icon
sweetcandysp

Thank you for your sharing, It is exactly what I was looking for slope 2

Profile icon
LauraLi3

Thanks for taking the time to share your findings - much appreciated!
I would like to recommend a game play solitaire, which is a great game you can enjoy

Profile icon
RishikDe

Excuse me, but could you tell me how to make the repl forever on? I use uptimeRobot to do the ping part, but the code to receive this ping? (server.js or something?) Please add it @ruiwenge2

Profile icon
jilljbently

It's really not easy to find this information, it's worth a lot of gold, thank you for everything. I would like to recommend the football legends game, which is a great game that I'm playing these days, to you.

Profile icon
Cole415

This is a great post. I like this topic. I found many interesting things from this site. Thanks for posting this again.https://www.mycardstatement.biz/

Profile icon
EagleEye2010

I get an error when I run 'const socket = io();' it says it is not a function!! Any help??

Profile icon
6w6

cool and good

Profile icon
themajikspoon

This is really useful, thanks

Profile icon
LolaBrown

Under the same government initiative comes the provision of free government phone stands

Profile icon
Howard4853
I recommend you a wonderful site reports that will help you write any written work.

https://www.rapidfs.run/

Profile icon
Timmons15

I really appreciated this piece. I often think of how much of a time suck and a mental drain diving into comment conversations can be. But sometimes it is worth it. At the end of the day, it's important to assert oneself and to attempt to have discussions about what matters to you.
https://www.rapidfs.org/

Profile icon
Hopkins54

Your article content is being very much interested, I am very impressed with your post. I hope to receive more great posts..
https://www.expresshr.me/

Profile icon
Glitchez

@ruiwenge2 what are the value and message parameters? is the message the actual text? and if so what is value for then?

Profile icon
Raegan2

Socket.IO is a library that enables real-time, bidirectional and event-based communication between the browser and the server. It consists of: a Node.

Profile icon
SamuelWaller1

Can you send a message from a client to another client, or can clients only send messages to the server?

Profile icon
DillonB07

@SamuelWaller1 You could make a client send a message to the server, and then the server sends it to the other clients. I don't think that you can send a message from a client to another client.

Profile icon
CodingElf66

What does socket.emit do? Does it just print the text on the webpage?

Profile icon
ruiwenge2

@CodingElf66 lol of course not, it sends a message to the server

Profile icon
CodingElf66