Last active
October 14, 2021 11:21
-
-
Save Srushtika/bad43787485913406a6df46d5a15571d to your computer and use it in GitHub Desktop.
WebSockets server tutorial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require('http'); | |
const crypto = require('crypto'); | |
const static = require('node-static'); | |
const file = new static.Server('./'); | |
const server = http.createServer((req, res) => { | |
req.addListener('end', () => file.serve(req, res)).resume(); | |
}); | |
server.on('upgrade', function (req, socket) { | |
if (req.headers['upgrade'] !== 'websocket') { | |
socket.end('HTTP/1.1 400 Bad Request'); | |
return; | |
} | |
// Read the websocket key provided by the client: | |
const acceptKey = req.headers['sec-websocket-key']; | |
// Generate the response value to use in the response: | |
const hash = generateAcceptValue(acceptKey); | |
// Write the HTTP response into an array of response lines: | |
const responseHeaders = [ 'HTTP/1.1 101 Web Socket Protocol Handshake', 'Upgrade: WebSocket', 'Connection: Upgrade', `Sec-WebSocket-Accept: ${hash}` ]; | |
// Write the response back to the client socket, being sure to append two | |
// additional newlines so that the browser recognises the end of the response | |
// header and doesn't continue to wait for more header data: | |
socket.write(responseHeaders.join('\r\n') + '\r\n\r\n'); | |
}); | |
// Don't forget the hashing function described earlier: | |
function generateAcceptValue (acceptKey) { | |
return crypto | |
.createHash('sha1') | |
.update(acceptKey + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', 'binary') | |
.digest('base64'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
All fixed, thanks!