How to make different users connect to the same socket?

783 views Asked by At

I'm writing a simple chat app using Node.js. The server-side code is :

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);

The problem is that, when a client connects to the server, the socket object is UNIQUE every time a client connects, so the different clients cannot exchange messages.

How I can make different users connect to same socket so they can exchange messages?

0

There are 0 answers