Help


Documentation & Tutorials

Getting Started with Socket.io

Socket.io Overview

Socket.io enables real-time event-based communication between one or more clients and a server. It works on every platform, browser or device and is fast and reliable. Socket.io has two parts: a client-side library that runs in the browser, and a server-side library for Node.js. Both components have an identical API.

In this tutorial we will cover setting up a basic Express.js application with Socket.io. We will create a simple chat server and show the basics on how a client and server works.

Requirements:

Before we begin, we assume that you have Node.js and NPM (Node Package Manager) installed. If not, we highly recommend downloading and installing NVM. NVM is a version manager for node.

Confirm that both tools are installed on your system by typing:

root@socket:~# node --version
v4.2.6
root@socket:~# npm --version
3.5.2

Installing Express.js and Socket.io

Express is a minimal and flexible Node.js web application framework.

1 . Create a folder that we will call myapp

mkdir myapp  
cd myapp

2 . Use npm init to create a package.json

npm init

The npm init command will create an empty project with a package.json file. If you like you can answer all the questions. If not just press enter through all of it.

3 . Install Express and Socket.io and save them to our package.json file for later

npm install socket.io express --save

4 . Install jquery

npm install jquery --save

Creating an Express Server

Let’s begin by creating an express server that displays Hello World.

1 . Create a new file in the socket-app folder.

mkdir app.js

2 . In the new fille called app.js, paste the following content

// app.js
var express = require('express');  
var app = express();  
var server = require('http').createServer(app);  
var io = require('socket.io')(server);

app.use(express.static(__dirname + '/node_modules'));  
app.get('/', function(req, res,next) {  
    res.sendFile(__dirname + '/index.html');
});

server.listen(4200);

In the app.js file above, we are requiring Express, and creating a new server. We are then requiring Socket.io.

We are setting the static folder to /node_modules since we are using npm to server up jQuery and we want to be able to reference it in our html.

App.get routes HTTP requests to the specified path with a specific call back function. The res object represents the HTTP response that an Express app sends when it gets a request. The sendFile just sends the file at the specific path. The server.listen will open a port and listen for requests coming in.

3 . Create an index.html file which will display a Hello World message

<!doctype html>  
<html lang="en">  
    <head>

    </head>
    <body>
        <h1>Hello World!</h1>
        <div id="future"></div>
        <form id="form" id="chat_form">
            <input id="chat_input" type="text">
            <input type="submit" value="Send">
        </form>
         <script src="/jquery/dist/jquery.js"></script>
        <script src="/socket.io/socket.io.js"></script>
    </body>
</html>

As you can see from the bottom the script src are pointing to files in our node_modules folder.

4 . Launch the server to make sure everything works

node app.js

5 . Open up a browser at http://Server_IP:4200. It should display the following

Hello_world

Connecting a Client to the Server using Socket.io

Let’s try to get the client to connect to the server with Socket.io and have it respond in the console.

1 . In the app.js file, edit the index.html to add this script to the bottom of the file

<!--Index.html-->  
...
<script>  
 var socket = io.connect('http://10.1.220.19:4200');
 socket.on('connect', function(data) {
    socket.emit('join', 'Hello World from client');
 });
</script>

The socket.on('connect') is an event which is fired upon a successful connection from the web browser. We then have a function callback that will send to the server the hello world message.

2 . Edit the app.js file to add just before the server.listen the following configuration. We’ve pasted the server.listen again in the example below as you should not forget closing parenthesis.

// app.js

io.on('connection', function(client) {
    console.log('Client connected...');
    client.on('join', function(data) {
       console.log(data);
    });
});

server.listen(4200);

The io.on is listening for connections. When it receives one it will report to the console client connected.... The 'client.on('join') will wait for a message from the client for join. It will then log it to the console.

3 . Launch the node again.

node app.js

ClientConnected

Setting up the Socket Server

Important: The following section can only work if your server is setup locally.

We need to configure the server so it replies to the client with a message.

1 . Add the emit line after console.log.

// app.js
io.on('connection', function(client) {
    console.log('Client connected...');
    client.on('join', function(data) {
       console.log(data);
       client.emit('messages', 'Hello from server');
    });
});

server.listen(4200);

The client.emit will send a message back to the client that just connected with a message using ‘messages’.

2 . Add a new socket.on messages event in the index.html.

// index.html
        socket.on('messages', function(data) {
                alert(data);
        });

Now when a client connects, it will send a message to the server and it will trigger a popup.

Excluding the Socket Server

In the previous examples we saw that we can send a message to the server and that we can also send a message back to the client. Now, if we need to send a message to all the clients excluding the socket that started it, it is also possible.

1 . Update the index.html

<script>
var socket = io.connect('http://51.15.244.129:4200');
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
});
socket.on('broad', function(data) {
    $('#future').append(data+ "<br/>");
});

$('form').submit(function(e){
e.preventDefault();
var message = $('#chat_input').val();
socket.emit('messages', message);
});

</script>

We added in a new JQuery .submit event handler which prevents the form from submitting and instead send a message to the server with the values of the input field in messages.

Also, we added a new socket event listener for ‘broad’ which updates our div with the message that was returned.

2 . Update the app.js

// app.js
...
io.on('connection', function(client) {
    console.log('Client connected...');
    client.on('join', function(data) {
        console.log(data);
        client.on('messages', function(data) {
            client.emit('broad', data);
            client.broadcast.emit('broad',data);
        });
    });
});
server.listen(4200);

You can see we are listening on messages. After receiving data we simply inform all other clients, including the socket that sent the message, the data.

If we restart the app.js file we will see we can now send messages to all other clients when we type anything into our input box and press submit. The div under the hello world message should update.

Discover a New Cloud Experience

Deploy SSD Cloud Servers in seconds.