Post

Web-Sockets - Socket.IO

This guide will demonstrate how to setup an express webserver that uses Socket.IO for communication.

  1. Installing Requirements
  2. Backend Code
  3. Frontend Code

Installing Requirements

Install the express and socket.io packages using the following command:

1
npm i express socket.io


Backend Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const express = require('express');
const path = require('path');
const fs = require('fs');
const ws = require('ws');
const app = express();

const HOSTNAME = 'testing.com';
const PORT = 8443;

// TLS Options
const serverOptions = {
	cert: fs.readFileSync(path.join(__dirname, 'certs/host.crt')),
	key: fs.readFileSync(path.join(__dirname, 'certs/host.key'))
}

const httpServer = require('https').Server(serverOptions, app);
const io = require('socket.io')(httpServer);

// New WebSocket Connection
io.on('connection', (socket) => {
	// Verify cookie is valid here
	let cookie = socket.handshake?.headers?.cookie || 'N/A';

	socket.on('/endpoint/1', (msg) => {
		console.log('/endpoint/1', msg);
	});

	socket.on('/endpoint/2', (msg) => {
		console.log('/endpoint/2', msg);
		socket.emit('/api/connected', 'Connection Success');
	});

	socket.on('/close-socket', () => {
		socket.disconnect();
	});

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

// Don't allow standard WebSocket Connections 
httpServer.on('upgrade', (request, socket) => {
	console.log('here');
	socket.destroy();
});

app.get('/', (req, res) => {
	res.sendFile(path.join(__dirname, 'index.html'));
});

// Start the Server
httpServer.listen(PORT, () => {
	console.log(`[-] Server Listening on Port ${PORT}`);
});


Frontend Code

Standard HTML Page

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html>
<head>
	<title>WebSocket - Socket IO</title>
</head>
<body>
	<h4>WebSocket - Socket IO</h4>

	<script src="/socket.io/socket.io.js"></script>
	<script>
		const socket = io('https://testing.com:8443');

		socket.on('connect', () => {
			console.log('CONNECTED');
			socket.emit('/endpoint/2', 'Test Message');
		});

		socket.on('disconnect', () => {
			console.log('DISCONNECTED');
		});

		socket.on('/api/connected', (msg) => {
			console.log(`MSG:`, msg);
		});

		setTimeout(() => {
			socket.emit('/endpoint/2', 'Test Message');
		}, 1000)
	</script>
</body>
</html>

React

To use Socket.IO with React we need to do the following:

1
npm i socket.io-client
1
2
3
import openSocket from 'socket.io-client';

let socket = openSocket('https://testing.com:8443');
  • You can then use the library as normal.
This post is licensed under CC BY 4.0 by the author.