July 2017
Intermediate to advanced
656 pages
16h 1m
English
In server.js, let's begin by requiring our dependencies:
const http = require('http') const fs = require('fs') const ws = require('ws')
Next we want to load public/index.html into memory (we'll write index.html shortly), create an HTTP server, and then enhance it with a WebSocket server:
const app = fs.readFileSync('public/index.html') const server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html') res.end(app) }) const wss = new ws.Server({server})
Now that we have our WebSocket server instance (wss), we can listen to its connection event:
wss.on('connection', (socket) => { socket.on('message', (msg) => { console.log(`Received: ${msg}`) console.log(`From IP: ${socket.upgradeReq.connection.remoteAddress}`) ...