我正在使用Node.js编写一个简单的聊天应用程序。服务器端代码是:
const net = require('net');
const HOST = 'localhost';
const PORT = 3000;
const server = net.createServer();
server.listen(PORT, HOST);
server.on('connection', (socket) => {
console.log(socket.localPort);
console.log(socket.remotePort);
console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
socket.on('data', (data) => {
console.log('DATA ' + socket.remoteAddress + ': ' + data);
// Write the data back to the socket, the client will receive it as data from the server
socket.write('You said "' + data + '"');
});
socket.on('close', () => {
console.log('CLOSED: ' + socket.remoteAddress +' '+ socket.remotePort);
});
socket.on('error', () => {
console.log('ERROR OCCURED:');
});
});
console.log('Server listening on ' + HOST +':'+ PORT);
问题在于,当客户端连接到服务器时,每次客户端连接时套接字对象都是唯一的,因此不同的客户端无法交换消息。
如何让不同的用户连接到同一套接字,以便他们可以交换消息?