Socket.IO – Hello world

Socket.IO – Hello world ”; Previous Next In the following chapter we will discuss the basic example using Socket.IO library along with ExpressJS. Example First of all, create a file called app.js and enter the following code to set up an express application − var app = require(”express”)(); var http = require(”http”).Server(app); app.get(”/”, function(req, res){ res.sendFile(”E:/test/index.html”); }); http.listen(3000, function(){ console.log(”listening on *:3000”); }); We will need an index.html file to serve, create a new file called index.html and enter the following code in it − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <body>Hello world</body> </html> To test if this works, go to the terminal and run this app using the following command − nodemon app.js This will run the server on localhost:3000. Go to the browser and enter localhost:3000 to check this. If everything goes well a message saying “Hello World” is printed on the page. Following is another example (this require Socket.IO), it will log “A user connected”, every time a user goes to this page and “A user disconnected”, every time someone navigates away/closes this page. 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”); }); //Whenever someone connects this gets executed io.on(”connection”, function(socket){ console.log(”A user connected”); //Whenever someone disconnects this piece of code executed socket.on(”disconnect”, function () { console.log(”A user disconnected”); }); }); http.listen(3000, function(){ console.log(”listening on *:3000”); }); The require(”socket.io”)(http) creates a new socket.io instance attached to the http server. The io.on event handler handles connection, disconnection, etc., events in it, using the socket object. We have set up our server to log messages on connections and disconnections. We now have to include the client script and initialize the socket object there, so that clients can establish connections when required. The script is served by our io server at ”/socket.io/socket.io.js”. After completing the above procedure, the index.html file will look as follows − <!DOCTYPE html> <html> <head><title>Hello world</title></head> <script src=”/socket.io/socket.io.js”></script> <script> var socket = io(); </script> <body>Hello world</body> </html> If you go to localhost:3000 now (make sure your server is running), you will get Hello World printed in your browser. Now check your server console logs, it will show the following message − A user connected If you refresh your browser, it will disconnect the socket connection and recreate. You can see the following on your console logs − A user connected A user disconnected A user connected Print Page Previous Next Advertisements ”;

Socket.IO – Environment

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 ”;

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 – 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 ”;