Socket.IO quickstart


Express

Install express:

$ npm install express

Create a basic 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>

Restart the server by pressing Ctrl-C in your terminal and then running npm start again.

After refreshing the browser page, the messages should show up in your browser and terminal console.

Now you can start sending and receiving events!

Demo

See Repl.it demo:



If you enjoyed this post, please consider supporting this site!