Last active
September 26, 2024 11:59
-
-
Save ErickWendel/f82d4c5a34646ffc12f7ae75bf20a051 to your computer and use it in GitHub Desktop.
Pure WebSocket Node.js Server using Native HTTP Module
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
// 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) | |
}); |
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 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
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.