Socket.IO – Environment ”; Previous Next To get started with developing using the Socket.IO, you need to have Node and npm (node package manager) installed. If you do not have these, head over to Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal. node –version npm –version You should get an output similar to − v14.17.0 6.14.13Open your terminal and enter the following in your terminal to create a new folder and enter the following commands − $ mkdir test-project $ cd test-proect $ npm init It will ask you some questions; answer them in the following way − This will create a ”package.json node.js” configuration file. Now we need to install Express and Socket.IO. To install these and save them to package.json file, enter the following command in your terminal, into the project directory − npm install –save express socket.io One final thing is that we should keep restarting the server. When we make changes, we will need a tool called nodemon. To install nodemon, open your terminal and enter the following command − npm install -g nodemon Whenever you need to start the server, instead of using the node app.js use, nodemon app.js. This will ensure that you do not need to restart the server whenever you change a file. It speeds up the development process. Now, we have our development environment set up. Let us now get started with developing real-time applications with Socket.IO. Print Page Previous Next Advertisements ”;
Category: socket.io
Socket.IO – Namespaces
Socket.IO – Namespaces ”; Previous Next Socket.IO allows you to “namespace” your sockets, which essentially means assigning different endpoints or paths. This is a useful feature to minimize the number of resources (TCP connections) and at the same time separate concerns within your application by introducing separation between communication channels. Multiple namespaces actually share the same WebSockets connection thus saving us socket ports on the server. Namespaces are created on the server side. However, they are joined by clients by sending a request to the server. Default Namespaces The root namespace ”/” is the default namespace, which is joined by clients if a namespace is not specified by the client while connecting to the server. All connections to the server using the socket-object client side are made to the default namespace. For example − var socket = io(); This will connect the client to the default namespace. All events on this namespace connection will be handled by the io object on the server. All the previous examples were utilizing default namespaces to communicate with the server and back. Custom Namespaces We can create our own custom namespaces. To set up a custom namespace, we can call the ”of” function on the server side − var app = require(”express”)(); var http = require(”http”).Server(app); var io = require(”socket.io”)(http); app.get(”/”, function(req, res){ res.sendFile(”E:/test/index.html”);}); var nsp = io.of(”/my-namespace”); nsp.on(”connection”, function(socket){ console.log(”someone connected”); nsp.emit(”hi”, ”Hello everyone!”); }); http.listen(3000, function(){ console.log(”listening on localhost:3000”); }); Now, to connect a client to this namespace, you need to provide the namespace as an argument to the io constructor call to create a connection and a socket object on client side. For example, to connect to the above namespace, use the following HTML − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src=”/socket.io/socket.io.js”></script> <script> var socket = io(”/my-namespace”); socket.on(”hi”,function(data){ document.body.innerHTML = ””; document.write(data); }); </script> <body></body> </html> Every time someone connects to this namespace, they will receive a ”hi” event displaying the message “Hello everyone!”. Print Page Previous Next Advertisements ”;
Socket.IO – Broadcasting
Socket.IO – Broadcasting ”; Previous Next Broadcasting means sending a message to all connected clients. Broadcasting can be done at multiple levels. We can send the message to all the connected clients, to clients on a namespace and clients in a particular room. To broadcast an event to all the clients, we can use the io.sockets.emit method. Note − This will emit the event to ALL the connected clients (event the socket that might have fired this event). In this example, we will broadcast the number of connected clients to all the users. Update the app.js file to incorporate the following − var app = require(”express”)(); var http = require(”http”).Server(app); var io = require(”socket.io”)(http); app.get(”/”, function(req, res){ res.sendFile(”E:/test/index.html”); }); var clients = 0; io.on(”connection”, function(socket){ clients++; io.sockets.emit(”broadcast”,{ description: clients + ” clients connected!”}); socket.on(”disconnect”, function () { clients–; io.sockets.emit(”broadcast”,{ description: clients + ” clients connected!”}); }); }); http.listen(3000, function(){ console.log(”listening on localhost:3000”); }); On the client side, we just need to handle the broadcast event − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src=”/socket.io/socket.io.js”></script> <script> var socket = io(); socket.on(”broadcast”,function(data){ document.body.innerHTML = ””; document.write(data.description); }); </script> <body>Hello world</body> </html> If you connect four clients, you will get the following result − This was to send an event to everyone. Now, if we want to send an event to everyone, but the client that caused it (in the previous example, it was caused by new clients on connecting), we can use the socket.broadcast.emit. Let us send the new user a welcome message and update the other clients about him/her joining. So, in your app.js file, on connection of client send him a welcome message and broadcast connected client number to all others. var app = require(”express”)(); var http = require(”http”).Server(app); var io = require(”socket.io”)(http); app.get(”/”, function(req, res){ res.sendFile(”E:/test/index.html”); }); var clients = 0; io.on(”connection”, function(socket){ clients++; socket.emit(”newclientconnect”,{ description: ”Hey, welcome!”}); socket.broadcast.emit(”newclientconnect”,{ description: clients + ” clients connected!”}) socket.on(”disconnect”, function () { clients–; socket.broadcast.emit(”newclientconnect”,{ description: clients + ” clients connected!”}) }); }); http.listen(3000, function(){ console.log(”listening on localhost:3000”); }); And your html to handle this event − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src=”/socket.io/socket.io.js”></script> <script> var socket = io(); socket.on(”newclientconnect”,function(data){ document.body.innerHTML = ””; document.write(data.description); }); </script> <body>Hello world</body> </html> Now, the newest client gets a welcome message and others get how many clients are connected currently to the server. Print Page Previous Next Advertisements ”;
Socket.IO – Rooms
Socket.IO – Rooms ”; Previous Next Within each namespace, you can also define arbitrary channels that sockets can join and leave. These channels are called rooms. Rooms are used to further-separate concerns. Rooms also share the same socket connection like namespaces. One thing to keep in mind while using rooms is that they can only be joined on the server side. Joining Rooms You can call the join method on the socket to subscribe the socket to a given channel/room. For example, let us create rooms called ”room-<room-number>” and join some clients. As soon as this room is full, create another room and join clients there. Note − We are currently doing this on the default namespace, i.e. ”/”. You can also implement this in custom namespaces in the same fashion. var app = require(”express”)(); var http = require(”http”).Server(app); var io = require(”socket.io”)(http); app.get(”/”, function(req, res){ res.sendfile(”index.html”); }); var roomno = 1; io.on(”connection”, function(socket){ socket.join(“room-“+roomno); //Send this event to everyone in the room. io.sockets.in(“room-“+roomno).emit(”connectToRoom”, “You are in room no. “+roomno); }) http.listen(3000, function(){ console.log(”listening on localhost:3000”); }); Just handle this connectToRoom event on the client. <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src=”/socket.io/socket.io.js”></script> <script> var socket = io(); socket.on(”connectToRoom”,function(data){ document.body.innerHTML = ””; document.write(data); }); </script> <body></body> </html> Now if you connect three clients, the first two will get the following message − You are in room no. 1 Leaving a Room To leave a room, you need to call the leave function just as you called the join function on the socket. For example − To leave room ”room-1”, socket.leave(“room-“+roomno); Print Page Previous Next Advertisements ”;
Socket.IO – Home
Socket.IO Tutorial PDF Version Quick Guide Resources Job Search Discussion Socket.IO enables real-time bidirectional event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed. Socket.IO is built on top of the WebSockets API (Client side) and Node.js. It is one of the most depended upon library on npm (Node Package Manager). Audience This tutorial has been created for anyone who has a basic knowledge of HTML, Javascript and Node.js work. After completing this tutorial, the reader will be able to build moderately complex real-time websites, back-ends for mobile applications and push notification systems. Prerequisites The reader should have a basic knowledge of HTML, JavaScript and Node.js. If the readers are not acquainted with these, we will suggest them to go through these tutorials first. We will be using Express to ease creating servers; it is not a prerequisite though. Print Page Previous Next Advertisements ”;