Skip to content

Instantly share code, notes, and snippets.

@phillippelevidad
Created November 14, 2023 13:01
Show Gist options
  • Save phillippelevidad/c3d8f5f5274129b515fb38416da970aa to your computer and use it in GitHub Desktop.
Save phillippelevidad/c3d8f5f5274129b515fb38416da970aa to your computer and use it in GitHub Desktop.
Chat implementation in Node.js using a Duplex
import net from "net";
import { Duplex } from "stream";
function createClient(socket) {
return new Duplex({
read(size) {
// This function is called when the stream wants to pull more data in.
// In this chat application example, data reading is handled by the socket's 'data' event,
// so you might not need to implement anything here.
},
write(chunk, encoding, callback) {
// This function is called when there is data to write to the stream.
// Write the chunk of data to the socket.
socket.write(chunk, encoding, callback);
},
// It's important to handle the end-of-stream condition properly.
final(callback) {
socket.end(callback);
},
});
}
const clients = [];
// Create a server
const server = net.createServer((socket) => {
const client = createClient(socket);
clients.push(client);
socket.on("data", (data) => {
// Broadcast message to all clients
clients.forEach((c) => {
if (c !== client) {
c.write(`Someone says: ${data}`);
}
});
});
socket.on("end", () => {
// Remove client from list when they disconnect
const index = clients.indexOf(client);
if (index !== -1) {
clients.splice(index, 1);
}
});
});
server.listen(3000, () => {
console.log("Chat server running on port 3000");
});
// To run:
// Start the server in one terminal window:
// $ node 5-duplex-chat.js
// Connect to the server in another terminal window:
// $ telnet localhost 3000
// Type messages in the telnet window and press enter to send.
// Messages will be broadcast to all connected clients.
// ---
// Can also use Node itself to connect to the server and send messages:
// $ node -e 'const net = require("net"); const client = net.createConnection({ port: 3000 }, () => { console.log("Connected to server!"); process.stdin.resume(); process.stdin.on("data", (data) => client.write(data)); }); client.on("data", (data) => console.log("Server:", data.toString()))'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment