Creating a Node HTTP server with Socket.IO

In order to get Socket.IO running, we need to have at least one client and one server set up to talk to each other. In this article, we will set up a basic Node HTTP server with the built-in Node HTTP module.

Let’s Start

To get started with Socket.IO, you will need to install Node.js. This can be downloaded from https://nodejs.org/.

Once Node.js is installed, you will need to create a project directory with the following command:

$ mkdir MyNodeApp

And create a new package.json file by entering the following command:

$ npm init

Now, you will need to install Socket.IO. You can use NPM to install Socket.IO by entering the following command in your terminal.

$ npm install socket.io --save

To create a Node HTTP server with Socket.IO, follow these steps:

Step 1

Create a new file called server.js. This will be your server-side code:

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

server = http.createServer(function (req, res) {
    fs.readFile(__dirname + '/index.html', function (err, data) {
      res.writeHead(200);
      res.end(data);
    });
});

server.listen(5000);
io = socketIO(server);

io.on('connection', function (socket) {
  socket.emit('greeting-from-server', {
      greeting: 'Hello World!'
  });
  socket.on('greeting-from-client', function (message) {
    console.log(message);
  });
});

Step 2

You may see that server.js will read a file called index.html. You’ll need to create this as well, as shown in the following code:

<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO</title>
 </head>
 <body>
   <script src="/socket.io/socket.io.js"></script>
   <script>
            var socket = io('http://localhost:3000');
            socket.on('greeting-from-server', function (message) {
                document.body.appendChild(
                    document.createTextNode(message.greeting)
                );
                socket.emit('greeting-from-client', {
                    greeting: 'Hello Server'
                });
            });
   </script>
 </body>
</html>

Step 3

With your two files in place, you an start your server by entering following command on your terminal from the same directory where your files are.

$ node server

This will start a new Node server on port 3000. Node can listen on any port, but we will specifically tell it to listen on port 3000 in our server.js file. If you navigate to http://localhost:3000, you should see a message that says Hello World in your browser:

Hellow World!

Step 4

You should also see a message on your terminal with an object that contains a message that says ‘Hello Server’:

$ node server

{ greeting: 'Hello Server' }

Congratulations! Your client and your server are now talking to each other.

How it Works

The browser displays a message that originated on the server, whereas the server displays a message that originated on the client. These messages are both relayed by Socket.IO

The client side also initializes a function, but in the client’s case, we need to pass a string containing the server and port number if the server is not running on port 80. In our case, we will run the server on port 3000, so we need to pass http://localhost:3000 in the io function.

The /socket.io/socket.io.js file is served dynamically by Socket.IO, so you don’t need to manually add this file anywhere. As long as your server and Socket.IO are set up correctly, the script will be present. There is also a CDN available to host your socket.io.js file. The current version can be found at https://socket.io/blog/socket-io/ .

The io.on(‘connection’) method in the server-side code listens for any new client-side socket connections. When the client loads a page with Socket.IO on the client side, a new connection will be created here.

When the server gets a new socket connection, it will emit a message to every available socket that says.

Hello Client

When the client gets this message, it will render it to the DOM. It also emits a message of its own that the server will listen for.

Muhammad Mubeen

Muhammad Mubeen

Mubeen is a full-stack web & mobile app developer who is very proficient in MEAN.js, Vue, Python, Ionic 4, Flutter, Firebase, ROR, and PHP. He has created multiple mobile and web applications. He is very passionate about sharing his knowledge.

Leave a Reply

Your email address will not be published. Required fields are marked *

Trending