将消息发送到特定的客户端套接字(从NodeJS服务器到Java客户端)

时间:2020-08-30 12:00:00

标签: node.js sockets

我有一个通过套接字进行通信的Java客户端和NodeJS服务器。我想使用Windows“ cmd”为每个客户端同时连接更多客户端。我的程序应该模拟一些登录/注销方案。我想要实现的是:

  • ClientA和ClientB都连接到服务器
  • ClientA登录(使用“登录用户名密码”之类的命令)
  • ClientB也登录,但使用与ClientA相同的用户名和密码
  • ClientA应该强制注销,而ClientB应该成功登录

我为每个客户端使用一个Java线程。我的问题是我不了解NodeJS如何向其中的每一个发送消息以宣布它们已登录/注销。唯一收到消息的人是最后一个从服务器请求内容的人(即想要登录的人)。

connection是当前的客户端-服务器连接。对于每个登录成功的连接,我将用户名存储在currentUsername键中。我将所有这些成功的登录名存储在connectionArray中。当新客户端要登录时,我将通过所有连接来查看是否已经有人使用该用户名登录了

节点服务器

var net = require('net')

var connectionArray = []

var server = net.createServer(function (connection) {

    connection.on('data', function (data) {

        let commandArray = data.toString().split(" ")

        if (commandArray[0] == "login") {

            for (let connectionElement of connectionArray) {
                if (connectionElement.currentUsername == requestedUsername) {
                    connectionElement.write(`We will log you out!\n`)
                    connection.write(`We will log you in!\n`)
                }
            }

            /* This Promise result is responsible for storing the connections
               I didn't yet treat the removing case of a logout */
            loginService.check(someParameters).then((response) => {
                connectionArray.push(connection)
            }, (rejected) => {
                connection.write(rejected.message)
            })
        }
    })
})

Main.java

public class Main {

    public static void main(String[] args) throws IOException {
        ClientThread clientThread = new ClientThread();
        clientThread.start();
    }
}

在ClientThread.java中登录的案例

    case "login":
    try {
        if (splitCommand[1] != null && splitCommand[2] != null) {
            out.write(commandLine);
            out.flush();

            String line = reader.readLine();
            System.out.println(line + "\n");
        }
    } catch (Exception e) {
        System.out.println("Please enter your username and password!\n");
    }
    break;

结果将是clientB将收到“我们将登录!”,但clientA将不会收到其消息。正确的方法是什么?非常感谢!

0 个答案:

没有答案