DEV Community

Cover image for Socket.io Basics
LoganVoisin
LoganVoisin

Posted on • Updated on

Socket.io Basics

Socket.io is web sockets made simple. Web sockets create a path between your client and back end so they can more easily talk to each other. Socket io is primarily composed of emitters and listeners. Emitters emit a signal out to either the client or the server. However, listeners listen for a signal also from either the client or server. Here in this overview view we'll be using a tech stack that consists of Node.js, version 14, Express.js for our server, and React.js as our client.
First up let’s look at the initial setup. We’ll want to make sure we have Node.js and Node Package Manager (npm) installed and up to date. We can check that with the

js which node

command. If you don’t get back a file path for Node.js you need to install it. If you do get a file path and it’s not version 14.x then what you can do is

js npx use 14

that command will change over your node version to version 14.x.
From there we can use Express.js to set up a server and React.js to make out client (see docs here https://expressjs.com/en/starter/hello-world.html , and https://reactjs.org/docs/hello-world.html for help). So we have our Express server set up, lets see what we need to start with Socket.io.

const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, { /* options */ });

io.on("connection", (socket) => {
  // ...
});

httpServer.listen(3000);
Enter fullscreen mode Exit fullscreen mode

Okay so what’s happening here? Well, First we create our express server at the top. Then we import, “createServer '' from http and then we import server from Socket.io! That's all pretty normal so far so let’s talk about what's different. So we create an express server and call it an app, then we use that to make a new http server. Now we use that http server to make a new Socket.io server. Okay, not too bad so far… Let’s look at, “io.on(“conection)” This is a listener. It’s looking for a default event called connection. This event is emitted when a user connects to the server, then it creates a new socket for that user! The best part is Socket.io keeps track of the sockets for us.
Let’s talk a little bit more about what a listener is. A listener listens for events, like the name suggests, and it’s identifiable with, “.on”. The first argument is the name of the event it’s listening for and the second argument is a callback that can have data for it’s argument. Here it's a socket which is unique for every user.
So that's how we listen for that event but what if we want to create a custom event? Well we’ll be using React.js for our front end so I’ll give you an example of how that will look.

import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';

const socket = io();

function App() {
  const [isConnected, setIsConnected] = useState(socket.connected);
  const [lastPong, setLastPong] = useState(null);

 useEffect(() => {
    socket.on('connect', () => {
      setIsConnected(true);
    });

  socket.on('disconnect', () => {
      setIsConnected(false);
    });

  socket.on('pong', () => {
      setLastPong(new Date().toISOString());
    });

  return () => {
      socket.off('connect');
      socket.off('disconnect');
      socket.off('pong');
    };
  }, []);

  const sendPing = () => {
    socket.emit('ping');
  }

  return (
    <div>
      <p>Connected: { '' + isConnected }</p>
      <p>Last pong: { lastPong || '-' }</p>
      <button onClick={ sendPing }>Send ping</button>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Here we can see some events being emitted with socket.emit. Socket.emit is how we send out an event to the server with Socket.io!
These are just some of the basics of Socket.io. There is even more to learn from their documentation. Which can be found here at https://socket.io

Top comments (0)