One of the demos that really convinced me of the power of Node was the simple TCP chat server that Ryan Dahl presented in this video: https://www.youtube.com/watch?v=jo_B4LTHi3I&t=28m23s
Here's what the code in the demo looked like:
const net = require('net');
const server = net.createServer();
const sockets = [];
server.on('connection', (socket) => {
sockets.push(socket);
socket.on('data', (message) => {
for (const current_socket of sockets) {
if (current_socket !== socket) {
current_socket.write(message);
}
}
});
socket.on('end', () => {
const index = sockets.indexOf(socket);
sockets.splice(index, 1);
});
});
server.listen(8000, () => console.log('tcp server listening on port 8000'));
The only TCP example I found on the Deno website is an echo server that looks like this:
const listener = Deno.listen({ port: 8080 });
console.log("listening on 0.0.0.0:8080");
for await (const conn of listener) {
Deno.copy(conn, conn);
}
It's nice and compact, but I haven't been able to use Deno.Conn
's read
and write
methods to turn this example into a TCP chat server. Any help would be much appreciated! I also think it would be a useful example to add to the website.