1

I am trying to build a socket server using Node.js. The server need to handle multiple TCP connections. Here is my code:

const HOST = '127.0.0.1';
const PORT = 5000;

var app = require('net')();
var sleep = require('sleep');

var server = net.createServer().listen(PORT, HOST);
server.on('connection', function(sock){
    console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
    var c = 0;
    while(true){
        sock.write(c.toString()+' ');
        c++;
        sleep.sleep(1);
    }
});
console.log('Server listening on ' + HOST + ':' + PORT);

How to handle all connections parallelly instead of queueing? Thanks :D

1
  • How to handle all connections parallelly instead of queueing? you are 'queuing' because you blocked the event loop with this while(true). this said, node is single thread, everything is sequential, but fast enough to give the feel it is //, for true //ism, use another language like go. Commented Dec 19, 2016 at 11:16

2 Answers 2

1

As already stated in the comments, you are blocking the event loop with while(true), instead try using setInterval instead, to achieve the desired result:

setInterval(function() {
    sock.write(c.toString()+' ');
    c++;
}, 1000)
Sign up to request clarification or add additional context in comments.

1 Comment

This answer is what I need. Thank you!
0

I'm not sure I understood your question.

But every client will trigger the server.on('connection'), request which will be available through your sock variable for as long as the user is still there. Instead of trying to block your server to remind of the user, you need to think of an event based configuration, which will have two kind of events sock.on which will get an event fired from the client and an emit event which will send data to the targeted client.

so you could imagine something like this

server.on('connection', function(sock){
    sock.on('event_name', function(data_received){ 
       // Some stuff
    });
    sock.emit("connected", {"message", "Hi From the server"});
});

I think socket.io is a great place to start

2 Comments

Thank you. I used to handle connections by creating a new thread when I write it in Java. Java is not an event driven language.
In case it might get helpfull there is a java client for socket io : github.com/socketio/socket.io-client-java

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.