0

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?

E.Omar
  • 109
  • 1
  • 11
  • 3
    A socket is a connection between 2 end points. Usually a server and a user. To exchange a message between multiple users, you need to store the sockets and emit a message through those. – Seblor Mar 17 '19 at 19:37
  • @Seblor What I did on the client side is I send a message to the server and then from the server write it back to the client and that's done correctly. But what I want to do is to make another client receive a the message message. – E.Omar Mar 18 '19 at 08:13
  • 1
    You should find your answer here : https://stackoverflow.com/questions/16280747/sending-message-to-a-specific-connected-users-using-websocket – Seblor Mar 18 '19 at 08:20
  • @Seblor That's helpful thank you so much. – E.Omar Mar 18 '19 at 08:29

0 Answers0