Skip to content

Instantly share code, notes, and snippets.

@ErickWendel
Last active September 26, 2024 11:59
Show Gist options
  • Save ErickWendel/f82d4c5a34646ffc12f7ae75bf20a051 to your computer and use it in GitHub Desktop.
Save ErickWendel/f82d4c5a34646ffc12f7ae75bf20a051 to your computer and use it in GitHub Desktop.
Pure WebSocket Node.js Server using Native HTTP Module
// make a request
const options = {
port: 1337,
host: 'localhost',
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket'
}
};
const protocol = 'http'
// if your protocol is https you will need to require https module instead of http
const http = require(protocol)
const req = http.request(options);
req.end();
req.on('upgrade', (res, socket, upgradeHead) => {
console.log('got upgraded!');
socket.on('data', data => {
console.log('client received', data.toString())
})
// keep sending messages
setInterval(() => {
socket.write('Hello!')
}, 500)
});
const http = require('http');
const port = 1337
// when curl http:localhost://1337
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('hey there');
});
server.on('upgrade', (req, socket, head) => {
const id = Date.now()
const headers = [
'HTTP/1.1 101 Web Socket Protocol Handshake',
'Upgrade: WebSocket',
'Connection: Upgrade',
''
].map(line => line.concat('\r\n')).join('')
socket.write(headers);
socket.on('data', data => {
console.log('server!', data.toString());
socket.write(`replying ${data.toString()} ${new Date().toISOString()}`)
});
socket.on('end', _ => { console.log(`${id} disconnected!`) })
});
// Now that server is running
server.listen(port, () => console.log('server runnig at', port));
@diegogit03
Copy link

INSANE!

@non-reai
Copy link

this doesn't work

@nin-jin
Copy link

nin-jin commented Jan 26, 2024

@KavandF
Copy link

KavandF commented Feb 8, 2024

nice

@ErickWendel
Copy link
Author

Thanks a lot for the comments my friends! I also have a blog post and a video showing how to integrate it with the web. as @nin-jin mentioned the Security Key is required. There I made the webserver be compatible with the browser API

@nin-jin
Copy link

nin-jin commented Feb 11, 2024

It should be borne in mind that several websocket frames may arrive in the buffer, and the last of them may be cut off and you need to wait for the next buffer to process it. You might be interested to take a look at my implementation:

Please note that I am pausing the websocket during processing to prevent asynchronous handlers from executing competitively.

@ocleo1
Copy link

ocleo1 commented Apr 4, 2024

Thanks!

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