Socket.IO quickstart


This post goes over how to get started with Socket.IO:

Express

Install express:

npm install express

Create an express app:

// index.js
const express = require('express');
const http = require('http');

const app = express();
const server = http.Server(app);

const PORT = 3000;
server.listen(PORT, () => console.log('Listening on *:' + PORT));

Create directory public, which will serve static files:

mkdir public

Create index.html:

echo 'Hello world' > public/index.html

Update the express app to serve the static directory:

// index.js
// ...
app.use(express.static('public'));

Start the server:

node index.js

Go to localhost:3000 in your browser to see Hello world:

open http://localhost:3000/

Socket.IO

Install socket.io:

npm install socket.io

Add Socket.IO to the server:

// index.js
// ...
const Server = require('socket.io');
const io = new Server(server);

io.on('connection', (socket) => {
  console.log('User connected:', socket.id);

  socket.on('disconnect', () => {
    console.log('User disconnected:', socket.id);
  });
});

Add Socket.IO to the client:

<!-- public/index.html -->
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
  socket.on('connect', function () {
    console.log('User connected');
  });
</script>

Press Ctrl-C to stop the server and then restart the server:

node index.js

Refresh the page to see messages show up in your browser and terminal console.

You can start sending and receiving events!

Demo

Replit example:



Please support this site and join our Discord!