简体   繁体   中英

Do I need multithreading for clients simultaneously receiving a message via a socket?

I have a client (Java) and a server (NodeJS). I want to simulate more clients communicating one with the other using the more Windows command-lines (cmd).

Everytime a client connects, I save the connection in an array. When one of the clients types "send", I go through a loop to send a message to all connected clients. But every time I do this, only the client that entered "send" will receive the response. A short version is this:

var net = require('net');
let clients = []

var server = net.createServer(function (connection) {
    connection.on('data', function (data) {

        clients.push(connection);
        let commandArray = data.toString().split(" ");

        if (commandArray[0] == "send") {
            for (i = 0; i < clients.length; i++) {
                console.log(clients[i].remotePort)
                clients[i].write("Hello!\n")
            }
        }
    }
}

I'm more interested in the idea of multiple clients than in any correction of the code (but if there's something that is really wrong there, please let me know). My guess is that I need to use more threads, one for each client, to do this, otherwise only one will be available to receive the message at a given moment. Am I right?

The customary architecture that is used in this case is to have a single thread that is "the gatekeeper," simply executing some kind of poll() loop, which then hands-off the work requests to a "stable of (thread or process) workers" by some kind of queue. (The completed work-items are then pushed onto another queue which is then handled by the same or a different thread.)

But Also(!) "This scenario is so utterly-commonplace" that you need to be sure that you are not – Actum Ne Agas... – "doing a thing already done." No matter what programming environment you are working in, "there simply has to be(!) 'an existing framework or bit of useful plumbing!!'"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM