我有一个通过套接字进行通信的Java客户端和NodeJS服务器。我想使用Windows“ cmd”为每个客户端同时连接更多客户端。我的程序应该模拟一些登录/注销方案。我想要实现的是:
我为每个客户端使用一个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将不会收到其消息。正确的方法是什么?非常感谢!