Websockets: Blazing Fast Data Exchange

How WebSockets Work

> curl -vv -X GET /socket.io/?EIO=3&transport=websocket&sid=SZYqXN8Nbv5nypCiAAAIAccept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Sec-WebSocket-Version: 13
Origin: http://127.0.0.1:2406
Sec-WebSocket-Extensions: permessage-deflate
Sec-WebSocket-Key: dXjMvP0KSh3Ts3ZgWh6UpA==
Connection: keep-alive, Upgrade
Upgrade: websocket
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: wogWuZGEra8NGMeREAPru5yDTDA=
Sec-WebSocket-Extensions: permessage-deflate

NodeJS Example

General Setup

websocket
├── client
│ ├── index.js
│ ├── node_modules
│ ├── package-lock.json
│ └── package.json
└── server
├── index.js
├── node_modules
├── package-lock.json
└── package.json

Implementing the Server

const express = require('express')app = express()app.get('/', (req, res) => {
res.send('WebSocket Test')
})
const backendServer = app.listen(3000, () => {
console.log(`BOOTING BACKEND on port 3000`)
})
const websocket = require('socket.io')
const websocket = require('socket.io')const config = {
serveClient: true,
pingInterval: 10000,
pingTimeout: 5000,
cookie: true
}
const io = websocket(backendServer, config)

Implementing the Client

const express = require('express')
const path = require('path')
const websocket = require('socket.io')
const app = express()app.use('/', express.static(path.join(__dirname, 'html')))app.get('/health', (req, res) => {
res.send('ok')
})
frontendServer = app.listen(8080, () => {
console.log(`BOOTING FRONTEND on port 8080`)
})
io = websocket(frontendServer)
<head>
...
<script src="/socket.io/socket.io.js"></script>
</head>
<head>
...
<script>
const socket = io('ws://localhost:3000')
</script>
</head>

Exchanging Messages between Client and Server

io.on('connection', socket => {
console.log(`+ client ${socket.id} has connected`)
})
io.on('connection', (socket) => {
# ...
setInterval( () => {
socket.emit('api:server-time', new Date().toTimeString());
}, 5000)
});
<script>
const socket = io('ws://localhost:3000');
socket.on('api:server-time', function (timeString) {
console.log("Update from Server", timeString);
el = document.getElementById('server-time')
el.innerHTML = timeString;
});
</script>

Exchange Server Time: Complete Source Code

Server

const express = require('express')app = express()app.get('/', (req, res) => {
res.send('WebSocket Test')
})
const backendServer = app.listen(3000, () => {
console.log(`BOOTING BACKEND on port 3000`)
})
const websocket = require('socket.io')const config = {
serveClient: true,
pingInterval: 10000,
pingTimeout: 5000,
cookie: true
}
const io = websocket(backendServer, config)io.on('connection', socket => {
console.log(`+ client ${socket.id} has connected`)
setInterval(() => {
socket.emit('api:server-time', new Date().toTimeString())
}, 5000)
})

Client

const express = require('express')
const websocket = require('socket.io')
const app = express()app.use('/', express.static(path.join(__dirname, 'html')))app.get('/health', (req, res) => {
res.send('ok')
})
frontendServer = app.listen(8080, () => {
console.log(`BOOTING FRONTEND on port 8080`)
})
io = websocket(frontendServer)
<!doctype html>
<html>
<head>
<title>WebSocket Demo</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/default.css">
</head>
<script src="/socket.io/socket.io.js"></script>
<body>
<section>
<h1>Server Time</h2>
<p>The current server time is:</p>
<div id="server-time" />
</section>
<script>
const socket = io('wss://localhost:3000');
socket.on('api:server-time', function (timeString) {
console.log("Update from Server", timeString);
el = document.getElementById('server-time')
el.innerHTML = 'Server time: ' + timeString;
});
</script>
</body>
</html>

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store