DEV Community

WestonDease
WestonDease

Posted on

 

Socket.io

Socket.io is a node package that enables realtime communication between clients and servers. This enables us to have clients interact with each other in realtime without even refreshing the page! Lets look at how this works.

If we were to have our app connect to the server with socket.io we would implement this code in our server:

const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);

This sets up our server to include socket.io but we need the app to make a connection. So also in our server we need to set up a connection statement to handle client connection. We include the following.

io.on('connection', function(socket){
console.log("we connected!");
//more code for socket.io here
}

This code should log "we connected!" on the backend when a client has connected. But connecting isn't enough, we want to send and receive messages. So to receive messages, inside the connection, we use:

//here we listen for an event called 'some-event'
socket.on('some-event', function(data) {
console.log(data);
io.emit('new-event', newData; //here newData is some contrived data
});

Now let's look at that last line with io.emit. Thats how we send events. If we place a listener in the app files like so:

socket.on('new-event', function(data) {
console.log(data);
});

This code listens for the new-event and console logs it on the console on the client side. This means that we now have all the parts to make this app communicate in real time. This comes with the benefits of changing data in our database and keeping it up to date across all clients. This is only the basics. We can make several different statements to include where our messages emit to. The current statement we have emits to all users. But we can do better than that. Here is a handy cheat sheet for all the emit types we can use:

https://socket.io/docs/emit-cheatsheet/

Top comments (0)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git