Skip to content

Instantly share code, notes, and snippets.

@Frastio10
Last active July 29, 2023 12:31
Show Gist options
  • Save Frastio10/77176f890044ba9c2297c1d08dbc2aba to your computer and use it in GitHub Desktop.
Save Frastio10/77176f890044ba9c2297c1d08dbc2aba to your computer and use it in GitHub Desktop.
NodeJS basic tcp socket client and server without external library
// nodejs provided this example already on https://nodejs.org/api/http.html#http_event_upgrade
// I changed some stuffs so I can understand it better.
const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('okay');
});
// upgrade to websocket
server.on('upgrade', (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');
// recieve the buffer that is sent from client and send it back,
// I don't use socket.pipe so i can get more understanding about it.
socket.on("data",buffer => {
console.log(buffer.toString())
socket.write(buffer.toString())
})
});
// Now that server is running
server.listen(1337, '127.0.0.1', () => {
// make a request
const options = {
port: 1337,
host: '127.0.0.1',
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket'
}
};
const req = http.request(options);
req.end();
req.on('upgrade', (res, socket, upgradeHead) => {
console.log('got upgraded!');
// send text buffer to server
socket.write("DATA FROM CLIENT");
socket.on("data", buffer => console.log(buffer.toString()))
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment