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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  1. DZone
  2. Coding
  3. JavaScript
  4. Getting Started with Socket.IO and Node.js

Getting Started with Socket.IO and Node.js

Chad Lung user avatar by
Chad Lung
·
May. 25, 12 · Interview
Like (3)
Save
Tweet
Share
143.52K Views

Join the DZone community and get the full member experience.

Join For Free

Node.js is not the cure for everything, however, it can certainly makes working with Websockets very easy when using the Socket.io library. Using websockets you can easily build realtime applications and even multi-player games. Today I’ll show you how to easily build a simple chat program using Node.js and Socket.io.

Note: To go through this article you will need to have Node.js installed and working correctly. You will also need some sort of text editor, I’ll be using WebStorm but anything you wish to use should work. Some of the code in this article has been modified from this excellent source: http://book.mixu.net/ch13.html

On you computer create a new folder somewhere convenient called: chat. Inside that folder you can add two files called: app.js and index.html

Let’s fill in the app.js file first.

var fs = require('fs')
    , http = require('http')
    , socketio = require('socket.io');

var server = http.createServer(function(req, res) {
    res.writeHead(200, { 'Content-type': 'text/html'});
    res.end(fs.readFileSync(__dirname + '/index.html'));
}).listen(8080, function() {
    console.log('Listening at: http://localhost:8080');
});

socketio.listen(server).on('connection', function (socket) {
    socket.on('message', function (msg) {
        console.log('Message Received: ', msg);
        socket.broadcast.emit('message', msg);
    });
});

The above code is pretty bare minimum for a chat server. The server sends the index.html file and listens for any incoming websockets. If you were to send a message like “hi” the format would look something like the following:

{"name":"message","args":["hi"]}

The index.html page is also very minimal and looks like the following:

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        $(function(){
            var iosocket = io.connect();

            iosocket.on('connect', function () {
                $('#incomingChatMessages').append($('<li>Connected</li>'));

                iosocket.on('message', function(message) {
                    $('#incomingChatMessages').append($('<li></li>').text(message));
                });
                iosocket.on('disconnect', function() {
                    $('#incomingChatMessages').append('<li>Disconnected</li>');
                });
            });

            $('#outgoingChatMessage').keypress(function(event) {
                if(event.which == 13) {
                    event.preventDefault();
                    iosocket.send($('#outgoingChatMessage').val());
                    $('#incomingChatMessages').append($('<li></li>').text($('#outgoingChatMessage').val()));
                    $('#outgoingChatMessage').val('');
                }
            });
        });
    </script>
</head>
<body>
Incoming Chat: <ul id="incomingChatMessages"></ul>
<br />
<input type="text" id="outgoingChatMessage">
</body>
</html>

The webpage is not very attractive but it works. Open two browsers preferably ones that support WebSockets (Chrome or Safari will work).

The next step is to install socket.io by doing the following in a terminal (or command prompt):

$ npm install socket.io

Run the app.js file:

$ node app.js

Now with your two browsers go to the following path and try it out: http://localhost:8080/

 

 

 

 

 

Node.js Socket.IO

Published at DZone with permission of Chad Lung, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Quick Pattern-Matching Queries in PostgreSQL and YugabyteDB
  • Building a Scalable Search Architecture
  • Utilize OpenAI API to Extract Information From PDF Files
  • Agile Transformation With ChatGPT or McBoston?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: