Web Sockets Tutorial

Spread the love

WebSockets can be used to implement a persistent duplex connection between your client and server. This is a simple tutorial to get you started.

Libraries

There are many libraries you can use for websockets, the most popular library for node.js is socket.io . There are also many open source libaries available for different server side languages and frameworks.

 

Tutorial

Our tutorial will use a nodejs backend and a regular javascript frontend.  We will use version 2 of socket.io

Server Side

In our node.js server, can install socket.io using npm

npm install socket.io --save

Next you can get a the socket object by passing in the http server

var io = require('socket.io')(http);

You can now use the socket object to receive and send data to and from the server

The io.connection function will be called when a client connects to the server, we get a socket object which is the socket of the client.

io.on('connection', function (socket) {

})

We can now use the socket.on message listener to listen for messages from the client

 socket.on('message', function (message) {});

When we want to send messages or data to the client from the server, we can use the emit event using the socket

socket.emit('message', data);

You can also emit message to all connect clients using the emit function

io.emit('some event', { for: 'everyone' });

If you need to send images and other media from the server, you will need to convert the media to a format such as a base64 string and then emit the base64 string.

 

Client Side

To use socket.io in the client side, you will need to add the socket.io client script, then you can get an instance of the client side socket

var socket = io.connect(url);

The url parameter is the location of the server.

Next like the server side , you can listen to messages from the server using the on message listener

socket.on("message", function (message) {})

And you can send data to the server by using the emit method

socket.emit("message", data);

 

To send data from one client to another client directly is currently not possible, you will have to send the data to the server and it make it to forward data to the intended client.