NavigationContentFooter
Jump toSuggest an edit

Getting started with Socket.io

Reviewed on 09 April 2024Published on 05 July 2018
  • Socket-io
  • npm
  • socket
  • javascript
  • node-js

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.

Learn how to install and use Socket.io with Express using the npm package manager, and create a simple chat server to see the basics of how a client and server work together.

Before you start

To complete the actions presented below, you must have:

  • A Scaleway account logged into the console
  • Owner status or IAM permissions allowing you to perform actions in the intended Organization
  • An SSH key
  • An Instance running Ubuntu Xenial or a later version
  • Root access to the Instances you want to manage
  • Installed Node.js and NPM (Node Package Manager) on your Instance

Installing Express.js and Socket.io

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

  1. Create a folder and change the directory. In this tutorial, we call the folder myapp.

    mkdir myapp
    cd myapp
  2. Use npm init to create a package.json.

    npm init

    The npm init command creates an empty project with a package.json file. You can answer all the questions or press enter through all of them if you do not want to.

  3. Install Express and Socket.io using the npm package manager, and save them to our package.json file for later.

    npm install socket.io express --save
  4. Install jQuery using npm.

    npm install jquery --save

Creating an Express server

  1. Create a new file in the myapp folder.

    nano app.js
  2. Paste the following code in the file, save, and exit.

    // 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);

    We use this file to require Express, to create a new server, and require Socket.io as well.

    We also use it to set the static folder to /node_modules since we use npm to serve up jQuery and we want to be able to reference it in our HTML code.

    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 sends the file to the specified path. The server.listen opens a port and listens for requests coming in.

  3. Create an index.html file in the myapp folder to display a Hello World message in the socket.

    nano index.html
  4. Paste the following content in the file:

    <!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>

    The src scripts point to files in our node_modules folder.

  5. Launch the server.

    node app.js
  6. Open a browser and enter http://<IP_address>:4200. It should display the following:

Connecting a client to a server using Socket.io

In the next steps, we connect the client 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 the 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 fired upon a successful connection from the web browser. We then have a function callback that sends the hello world message to the server.

  2. Edit the app.js file to add the following configuration. Add the configuration before server.listen.

    // app.js
    io.on('connection', function(client) {
    console.log('Client connected...');
    client.on('join', function(data) {
    console.log(data);
    });
    });
    server.listen(4200);
    • io.on - is listening for connections. When it receives one it will report to the console client connected....
    • 'client.on('join') - waits for a message from the client to join. It will then log in to the console.
  3. Launch node again.

    node app.js

Setting up the Socket server

Important

You must set up your server locally before following the next steps.

  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);
    • client.emit will send a message back to the client that just connected with a message using ‘messages’.
  2. Add a new socket.on message event in the index.html.

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

    When a client connects now, it will send a message to the server and it will trigger a pop-up.

Excluding the Socket server

In the previous examples, we learned that we can send a message to the server and also send one back to the client. You can also send a message to all the clients excluding the socket that started it.

  1. Update the index.html file as follows.

    <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 a new JQuery .submit event handler which prevents the form from submitting and instead sends 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 returned.

  2. Update the app.js file.

    // 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 to messages. After receiving data we inform all other clients, including the socket that sent the message.

    If we restart the app.js file using node, we will be able to send messages to all other clients when we type anything into our input box and press submit. The div under the hello world message updates.

Docs APIScaleway consoleDedibox consoleScaleway LearningScaleway.comPricingBlogCarreer
© 2023-2024 – Scaleway