You must set up your server locally before following the next steps.
Getting started with Socket.io
- 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.
-
Create a folder and change the directory. In this tutorial, we call the folder
myapp
.mkdir myappcd myapp -
Use
npm init
to create a package.json.npm initThe
npm init
command creates an empty project with apackage.json
file. You can answer all the questions or press enter through all of them if you do not want to. -
Install Express and Socket.io using the
npm
package manager, and save them to ourpackage.json
file for later.npm install socket.io express --save -
Install jQuery using
npm
.npm install jquery --save
Creating an Express server
-
Create a new file in the
myapp
folder.nano app.js -
Paste the following code in the file, save, and exit.
// app.jsvar 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. Theres
object represents the HTTP response that an Express app sends when it gets a request. ThesendFile
sends the file to the specified path. Theserver.listen
opens a port and listens for requests coming in. -
Create an
index.html
file in themyapp
folder to display aHello World
message in the socket.nano index.html -
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. -
Launch the server.
node app.js -
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.
-
In the
app.js
file, edit theindex.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 thehello world
message to the server. -
Edit the
app.js
file to add the following configuration. Add the configuration beforeserver.listen
.// app.jsio.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 consoleclient connected...
.'client.on('join')
- waits for a message from the client tojoin
. It will then log in to the console.
-
Launch
node
again.node app.js
Setting up the Socket server
-
Add the
emit
line after console.log.// app.jsio.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’.
-
Add a new
socket.on
message event in theindex.html
.// index.htmlsocket.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.
-
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.
-
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 usingnode
, 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.