Skip to content

Instantly share code, notes, and snippets.

@modster
Created December 15, 2021 03:16
Show Gist options
  • Save modster/95aa0431490e9a1087f269098c9092aa to your computer and use it in GitHub Desktop.
Save modster/95aa0431490e9a1087f269098c9092aa to your computer and use it in GitHub Desktop.
Websockets
//https://nodejs.org/docs/v0.10.40/api/http.html#http_event_upgrade_1
var http = require('http');
// Create an HTTP server
var srv = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('okay');
});
srv.on('upgrade', function(req, socket, head) {
socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
'Upgrade: WebSocket\r\n' +
'Connection: Upgrade\r\n' +
'\r\n');
socket.pipe(socket); // echo back
});
// now that server is running
srv.listen(1337, '127.0.0.1', function() {
// make a request
var options = {
port: 1337,
hostname: '127.0.0.1',
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket'
}
};
var req = http.request(options);
req.end();
req.on('upgrade', function(res, socket, upgradeHead) {
console.log('got upgraded!');
socket.end();
process.exit(0);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment