Skip to content

Instantly share code, notes, and snippets.

@hongbo-miao
Last active October 15, 2019 23:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hongbo-miao/d6b29aa05562c7cbee8d8ba217cb9303 to your computer and use it in GitHub Desktop.
Save hongbo-miao/d6b29aa05562c7cbee8d8ba217cb9303 to your computer and use it in GitHub Desktop.
Chat
// 1. Server
// node index.js
//
// 2. Client
// 1) Start
// telnet localhost 3001
//
// 2) Quit
// Click Ctrl + ], then Ctrl + C
const net = require('net');
const clients = new Map();
const names = new Set();
const cache = [];
const server = net.createServer((socket) => {
console.log('client connected');
socket.write('Welcome to my chat server! What is your nickname?\n');
clients.set(socket, null);
let myName = null;
let isNickname = true;
socket.on('data', buffer => {
const msg = buffer.toString();
if (isNickname) {
if (names.has(msg)) {
socket.write('Please select new name\n');
} else {
// Connected with
socket.write(`You are connected with ${names.size} other users: ${Array.from(names).toString()}\n`);
// Print last 10 messages
cache.forEach(m => {
socket.write(m);
});
// Notify the rest of users you joined the chat
myName = msg.trim();
clients.forEach((name, s) => {
if (socket !== s) {
s.write(`*${myName} has joined the chat*\n`);
}
});
clients.set(socket, msg);
names.add(msg);
isNickname = false;
}
} else {
// Cache messages
const time = new Date();
const m = `[${time}] <${myName}> ${msg}`;
if (cache.length < 10) {
cache.push(m);
} else {
cache.shift();
cache.push(m);
}
// Broadcast
clients.forEach((name, s) => {
if (socket !== s) {
s.write(m);
}
});
}
});
socket.on('end', () => {
// Notify someone left the chat
clients.forEach((name, s) => {
if (socket !== s) {
const time = new Date();
s.write(`*${myName} has left the chat\n`);
}
});
names.delete(clients.get(socket));
clients.delete(socket);
console.log('client disconnected');
});
}).on('error', (err) => {
throw err;
});
server.listen(3001, '127.0.0.1');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment