By clicking or navigating this website site, you agree to allow our collection of information on Scaleway to offer you an optimal user experience and to keep track of statistics through cookies. Learn more about our Cookie Policy.

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.

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

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

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.

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.