DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Capture Node.js Garbage Collection Traces
  • Creating a Secure REST API in Node.js
  • Develop a Scraper With Node.js, Socket.IO, and Vue.js/Nuxt.js
  • Streamlining Event Data in Event-Driven Ansible

Trending

  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  • GDPR Compliance With .NET: Securing Data the Right Way
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  1. DZone
  2. Coding
  3. JavaScript
  4. Getting Started With Node.JS and Socket.io

Getting Started With Node.JS and Socket.io

With a little JavaScript know-how, you can learn how to get started with Socket.io and Node.JS to create a chat app with this tutorial.

By 
Sankalp Bhamare user avatar
Sankalp Bhamare
·
Jun. 09, 17 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
24.5K Views

Join the DZone community and get the full member experience.

Join For Free

Create your first Node and Socket.io chat app using Express.

Requirements

1. Install Node.JS and Git.

2. A little JavaScript experience.

Creating the App

1. Go to your project directory. It must be empty!

2. Open your terminal there and run this command:

           npm init 

Image title

Make sure to specify: entry-point: server.js.

Installing All Required Modules

  • Express:  npm install express --save
  • Socket.io:  npm install socket.io --save  

Run: npm install 

Make sure that there are no errors.

Let's Start Coding

Create a server.jsfile.

Creating and Deploying a Basic Express Server

server.js:

var express = require('express');//Importing Express
var app = express();//Getting App From Express
const port = 8080;//Creating A Constant For Providing The Port
app.listen(port);//Telling Express App To Listen To Port
//Routing Request : http://localhost:port/
app.get('/',function(request,response){
  //Telling Browser That The File Provided Is A HTML File
  response.writeHead(200,{"Content-Type":"text/html"});
  //Passing HTML To Browser
  response.write("The Server Is <strong>Working</strong>!");
  //Ending Response
  response.end();

})
console.log("Server Running At:localhost:"+port);

Deploy the Server

Run:npm start

Your console will show you this:

D:\dzonetutorial>npm start

 > dzonetutorial@1.0.0 start D:\dzonetutorial

 > node server.js
 Server Running At:localhost:8080

Now check if it is working:

Open Chrome and navigate to localhost:8080.

If you see something like this:Image titleThen your server is working perfectly!

If you get an error that says "site not found," "access denied," or you do not see the message above, then it may be an issue with your firewall. The node may not have access to open ports. Here is how to fix that.

Loading an HTML File Through the Server

For simplicity, I am not using Jade, EJS or any View Engine.

 server.js: 

var express = require('express');//Importing Express
var app = express();//Getting App From Express
var fs = require('fs');//Importing File System Module To Access Files
const port = 8080;//Creating A Constant For Providing The Port
app.listen(port);//Telling Express App To Listen To Port
//Routing Request : http://localhost:port/
app.get('/',function(request,response){
  //Telling Browser That The File Provided Is A HTML File
  response.writeHead(200,{"Content-Type":"text/html"});
  //Passing HTML To Browser
  response.write(fs.readFileSync("./public/index.html"));
  //Ending Response
  response.end();

})
//Routing To Public Folder For Any Static Context
app.use(express.static(__dirname + '/public'));
console.log("Server Running At:localhost:"+port);

Now create a folder named Public in the root directory, and inside it, create a file named index.html.

 index.html: 

<!DOCTYPE html>
 <html> 
    <head>
        <meta charset="utf-8">
        <title>Test Page</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        Hello Node Server Routing Is Working.       
    </body>
</html>

Stop the execution of the previous server by pressing Ctrl+C in your console.

Deploy this new server: npm start  

When you open http://localhost:8080 you should see that public/index.html is loaded.

Now Let's Start Using Socket.io

First we have to start the Socket.io sub-server on the main server.

In server.js:

  Replace:  app.listen(port); 

  with:   var io = require('socket.io').listen(app.listen(port)); 

This gives Socket.io access to the server so that it can serve the socket.io.js to the public/index.html.

Information on Socket.io

In order to enable realtime fast communication with the server and frontend, Socket.io is used, which passes requests from the client side to the server side.

In socket.io, there are two scripts, one running on the client side and the other on the server side. Both are similar, but run on different platforms; client side socket.io can control the appearance and the GUI, whereas the server side one can control all server side tasks.

The transfer of data is handled through events which are triggered by the  emit  function in the Socket.io core. These events are recieved through the  on  function, which has a  callback  function to which the data sent through  emit  is passed.

Before the transfer of data starts the client side has to connect to this Socket.io sub-server built on top of the express server. When the client side connects to the server, the 'connection'  event is triggered for the Socket.io running at the server. It is the same with the  'disconnect'  event.

Example:

//For Tracking When User Connects:
io.sockets.on("connection",function(socket){
//var socket is the socket for the client who has connected.
})
//For Tracking When User Disconnects:
io.sockets.on("disconnect",function(socket){
//var socket is the socket for the client who has disconnected.
})

 This is how a  'connection'  event and a 'disconnect'  event are recieved by the server.

 How An Event Is Triggered: 

io.sockets.emit("EVENT_NAME",EVENT_DATA);
//EVENT_DATA Can Be Anything That Is To Be Sent To The Server

 How An Event Is Handled: 

io.sockets.on("EVENT_NAME",function(data){
//data = EVENT_DATA Passed From The emit Method
})

This will give you a small idea about Socket.io and its powers.

Using Socket.io on the Client Side

index.html:

<!DOCTYPE html>
 <html> 
    <head>
        <meta charset="utf-8">
        <title>Test Page</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <!--socket.io.js is automatically added by node-->
        <script src="socket.io/socket.io.js"></script>
        <!--jQuery Used For Some Frontend Tasks-->
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script>
            //Connecting To socket.io
            var socket = io.connect(window.location.host);
            socket.on("Start_Chat",function(){
                alert("Ready!");
            })
        </script>      
    </body>
</html>

server.js:

var express = require('express');//Importing Express
var app = express();//Getting App From Express
var fs = require('fs');//Importing File System Module To Access Files
const port = 8080;//Creating A Constant For Providing The Port
//Routing Request : http://localhost:port/
app.get('/',function(request,response){
  //Telling Browser That The File Provided Is A HTML File
  response.writeHead(200,{"Content-Type":"text/html"});
  //Passing HTML To Browser
  response.write(fs.readFileSync("./public/index.html"));
  //Ending Response
  response.end();

})
//Routing To Public Folder For Any Static Context
app.use(express.static(__dirname + '/public'));
console.log("Server Running At:localhost:"+port);
var io = require('socket.io').listen(app.listen(port));//Telling Express+Socket.io App To Listen To Port
io.sockets.on("connection",function(socket){
    socket.emit("Start_Chat");
})

Instead of io.sockets.emit(...) , socket.emit(...)   is used because the 'Start_Chat' event must only be triggered to the client who just connected.

Stop the execution of the previous server by pressing Ctrl+C in your console and deploy this new server: npm start 

Output: 

Image title

 An alert of 'Ready!' should be given to prove that socket.io is working.

Designing a Chat UI in Raw HTML

index.html:

<!DOCTYPE html>
 <html> 
    <head>
        <meta charset="utf-8">
        <title>Chat Page</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <!--socket.io.js is automatically added by node-->
        <script src="socket.io/socket.io.js"></script>
        <!--jQuery Used For Some Frontend Tasks-->
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
       <p id="stat"><strong>Status:</strong>Not Connected</p>
       <h2>Socket.io Chat Tutorial:</h2>
       <ul>

       </ul>
       <input id="field" placeholder="Wait..." type="text"><input type="button" value="Go" id="btn">
        <script>
            //Connecting To socket.io
            var socket = io.connect(window.location.host);
            socket.on("Start_Chat",function(){
                //Setting Message On Connection..
                $("#stat").html("<strong>Status:</strong>Connected");              
            })
            socket.on("disconnect",function(){
                //Setting Message On Disconnection
                $("#stat").html("<strong>Status:</strong>Disconnected From Server Refresh!");
            })
        </script>      
    </body>
</html>

Now let's modify server.js to send data from one socket to another.

server.js:

var express = require('express');//Importing Express
var app = express();//Getting App From Express
var fs = require('fs');//Importing File System Module To Access Files
const port = 8080;//Creating A Constant For Providing The Port
//Routing Request : http://localhost:port/
app.get('/',function(request,response){
  //Telling Browser That The File Provided Is A HTML File
  response.writeHead(200,{"Content-Type":"text/html"});
  //Passing HTML To Browser
  response.write(fs.readFileSync("./public/index.html"));
  //Ending Response
  response.end();

})
//Routing To Public Folder For Any Static Context
app.use(express.static(__dirname + '/public'));
console.log("Server Running At:localhost:"+port);
var io = require('socket.io').listen(app.listen(port));//Telling Express+Socket.io App To Listen To Port
io.sockets.on("connection",function(socket){
    socket.emit("Start_Chat");
    //On Event Registar_Name
    socket.on("Register_Name",function(data){
       io.sockets.emit("r_name","<strong>"+data+"</strong> Has Joined The Chat");
       //Now Listening To A Chat Message
       socket.on("Send_msg",function(data){
       io.sockets.emit("msg",data);
       //Now Listening To A Chat Message

    })
    })
})

Finally, we are finished with the Node.Js side of the tutorial; now it's the client side:

index.html:

<!DOCTYPE html>
 <html> 
    <head>
        <meta charset="utf-8">
        <title>Chat Page</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <!--socket.io.js is automatically added by node-->
        <script src="socket.io/socket.io.js"></script>
        <!--jQuery Used For Some Frontend Tasks-->
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
       <p id="stat"><strong>Status:</strong>Not Connected</p>
       <h2>Socket.io Chat Tutorial:</h2>
       <ul></ul>
       <input id="field" placeholder="Wait..." type="text"><input type="button" value="Go" id="btn">
        <script>
            //Connecting To socket.io
            var socket = io.connect(window.location.host);
            socket.on("Start_Chat",function(){
                //Setting Message On Connection..
                $("#stat").html("<strong>Status:</strong>Connected");
                $("#field").attr("placeholder","Your Name..");
                $("#field").focus();              
            })
            socket.on("disconnect",function(){
                //Setting Message On Disconnection
                $("#stat").html("<strong>Status:</strong>Disconnected From Server Refresh!");
            })
            $("#btn").click(function(){
                if($("#field").attr("placeholder") ==="Your Name.."){
                     socket.emit("Register_Name",$("#field").val());
                     $("#field").val("");
                     $("#field").attr("placeholder","Your Text..");
                } else if($("#field").attr("placeholder") == "Your Text.."){
                     socket.emit("Send_msg",$("#field").val());
                     $("#field").val("");
                     $("#field").focus();
                }else alert("Wait...");
            })
            socket.on("r_name",function(data){
                $("ul").append("<li>"+data+"</li>");
            })
            socket.on("msg",function(data){
                $("ul").append("<li>"+data+"</li>");
            })
        </script>      
    </body>
</html>

Stop the execution of the previous server by pressing Ctrl+C in your console to deploy this new server: npm start 

Output:




Socket.IO Node.js Event Express

Opinions expressed by DZone contributors are their own.

Related

  • How To Capture Node.js Garbage Collection Traces
  • Creating a Secure REST API in Node.js
  • Develop a Scraper With Node.js, Socket.IO, and Vue.js/Nuxt.js
  • Streamlining Event Data in Event-Driven Ansible

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!