Post

Web-Sockets - Native

This guide will demonstrate how to setup an express webserver that uses built-in browser WebSockets for communication.

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

Installing Requirements

Install the express & ws packages using the following command:

1
npm i express ws


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
56
57
58
59
60
61
62
63
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 webSocketServer = new ws.Server({ noServer: true });

// Handle WebSocket Connections (After Upgrade)
webSocketServer.on('connection', (socket, req) => {
	console.log('New WebSocket connection', req.socket.remoteAddress);

	socket.on('message', (msg) => {
		console.log('New MSG:', msg);
		socket.send('Received');
	});

	socket.on('error', (err) => {
		console.log('ERROR:', err);
		socket.terminate();
	});
});

// Handle WebSocket Upgrade
httpServer.on('upgrade', (request, socket, head) => {
	// Connection IP
	console.log(`Remote Address: ${socket.remoteAddress}`);

	// Check the Origin is correct, prevent CSWSH (Cross-Site Web-Socket Hijacking)
	if (request.headers.origin === `https://${HOSTNAME}:${PORT}`) {

		// Check Cookie is valid here
		console.log(request.headers.cookie);

		// Upgrade the connection to a WebSocket
		webSocketServer.handleUpgrade(request, socket, head, (newSocket) => {
			webSocketServer.emit('connection', newSocket, request)
		});
	} else {
		// Origin was incorrect, reject connection
		socket.write('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');
		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

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
<!DOCTYPE html>
<html>
<head>
    <title>WebSockets - Native</title>
</head>
<body>
    <h4>WebSockets - Native</h4>

    <script>
        connectSocket = (url, params) => {
            let socket = new WebSocket(url, params);

            socket.onopen = () => {
                console.log("OPENED");
                socket.send('Test Message');
            }

            socket.onmessage = (msg) => {
                console.log(`MSG: "${msg.data}"`);
            }

            socket.onerror = (err) => {
                console.log("ERROR", err);
            }

            socket.onclose = () => {
                console.log("CLOSED");
            }

            return socket;
        }

        let socket = connectSocket('wss://testing.com:8443');
    </script>
</body>
</html>
This post is licensed under CC BY 4.0 by the author.