0

I create a server with Node.js:

var net = require('net');

var PORT = 8181;

var server = net.createServer(

  function(socket) {
    console.log(this.address());

    socket.on('data', function(data) {
      var msg = data.toString().replace(/\n$/, '');
      console.log('got: ' + msg);
    });

    process.stdin.on('readable',

      function() {

        var chunk = process.stdin.read();

        if (chunk !== null) {

          socket.write(chunk);
        }
      }
    )

    socket.write('heyyo\n');
  }
)

Now, when multiple connections are coming in, this server sends out the typed in line only to the first connection.

I have two questions:

  • what is a standard way to handle this, i.e. to store the incoming sockets into an array?

  • exactly what happens that causes the readable event not to reach the other connections' callback function?

1 Answer 1

2

I would highly recommend using a library like socket.io. It makes handling connect/disconnect as well as placing sockets in rooms very simple. Additionally you can get the full list of available rooms and connected sockets through the adapter class it offers. A functional example is available in the docs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.