Skip to content

Instantly share code, notes, and snippets.

@anak10thn
Forked from ErickWendel/websocket-client.js
Created March 2, 2023 12:11
Show Gist options
  • Save anak10thn/c65ce732e6060ad1e03118849de5afde to your computer and use it in GitHub Desktop.
Save anak10thn/c65ce732e6060ad1e03118849de5afde 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));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment