Skip to content

Instantly share code, notes, and snippets.

@Srushtika
Last active October 14, 2021 11:21
Show Gist options
  • Save Srushtika/bad43787485913406a6df46d5a15571d to your computer and use it in GitHub Desktop.
Save Srushtika/bad43787485913406a6df46d5a15571d to your computer and use it in GitHub Desktop.
WebSockets server tutorial
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');
}
@meszaros-lajos-gyorgy
Copy link

There is some funkyness on line 13

@ofirdagan
Copy link

There is some funkyness on line 13

yeah, @Srushtika you should break a line

@balazimichal
Copy link

If you are getting an error: Error during WebSocket handshake: Incorrect 'Sec-WebSocket-Accept' header value - the error is in the generateAcceptValue. '258EAFA5-E914–47DA-95CA-C5AB0DC85B11' string between 4-4 character contains long dash instead of short. Once you fix this, you should be able to connect the client with no issues.

@Srushtika
Copy link
Author

All fixed, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment