Socket.io Basics

Advertisement

Advertisement

Intro

This is the very basics of using Socket.io.

Two other articles that may be relevant:

Installation

You need socket.io at a minimum. The others are optional.

npm install express socket.io bufferutil utf-8-validate

Project structure

There are two primary files. The index.html for the client, and server.js for the server.

The directory structure looks like:

public/
public/index.html
public/socket.io.min.js
server.js

public/index.html:

Either host the socket.io.min.js file in the public/ directory or use the CDN.

<!-- public/index.html -->
<html>
<head>
    <!-- https://socket.io/docs/v4/ -->

    <!-- <script src="https://cdn.socket.io/4.4.0/socket.io.min.js"></script> -->
    <script src="/socket.io.min.js"></script>

    <script>
        const socket = io("ws://localhost:3000");

        socket.on("connect", () => {
            // either with send()
            socket.send("Hello!");

            // or with emit() and custom event names
            socket.emit("salutations", "Hello!", { "mr": "john" }, Uint8Array.from([1, 2, 3, 4]));
        });

        // Handle standard event (sent with socket.send())
        socket.on("message", data => {
            console.log(data);
        });

        // Handle custom event from server (sent with socket.emit())
        socket.on("greetings", (elem1, elem2, elem3) => {
            console.log(elem1, elem2, elem3);
        });
    </script>
</head>
<body>
</body>
</html>

server.js:

In the server, you create an express app, then an http server that wraps the express app. Then you create the socket.io server taps into the http server. Finally, after creating all the express routes and socket.io callbacks, start the http server.

// server.js
// npm install express socket.io
// Optional
// npm install bufferutil utf-8-validate

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

const expressApp = express();
const httpServer = http.createServer(expressApp);

socketioOptions = {
    cors:
    {
        origin: "http://localhost:3000",
        methods: ["GET", "POST"]  
    },
}
const io = new Server(httpServer, socketioOptions);

/**
 * Express.js Routes
 */

expressApp.use('/', express.static(path.join(__dirname, 'public')))


/**
 * Socket.io Handlers
 */

io.on("connection", socket => {
    // either with send()
    socket.send("Hello!");

    // or with emit() and custom event names
    socket.emit("greetings", "Hey!", { "ms": "jane" }, Buffer.from([4, 3, 3, 1]));

    // handle the event sent with socket.send()
    socket.on("message", (data) => {
        console.log(data);
    });

    // handle the event sent with socket.emit()
    socket.on("salutations", (elem1, elem2, elem3) => {
        console.log(elem1, elem2, elem3);
    });
});

/**
 * Start server
 */
httpServer.listen(3000, () => { console.log('Visit http://localhost:3000/'); });

Running

Run server with node server.js.

Then open browser and visit http://localhost:3000/

References

Advertisement

Advertisement