Node.js 将消息发送到特定的客户端套接字(从NodeJS服务器发送到Java客户端)
我有一个Java客户端和一个通过套接字进行通信的NodeJS服务器。我想让更多的客户端同时连接使用Windows“cmd”为每一个。我的程序应该模拟一些登录/注销场景。我想要实现的是:Node.js 将消息发送到特定的客户端套接字(从NodeJS服务器发送到Java客户端),node.js,sockets,Node.js,Sockets,我有一个Java客户端和一个通过套接字进行通信的NodeJS服务器。我想让更多的客户端同时连接使用Windows“cmd”为每一个。我的程序应该模拟一些登录/注销场景。我想要实现的是: ClientA和ClientB都连接到服务器 ClientA登录(使用类似“登录用户名密码”的命令) ClientB也会登录,但使用与ClientA相同的用户名和密码 ClientA应强制注销,而ClientB应成功登录 我为每个客户机使用一个Java线程。我的问题是,我不明白我的节点如何能为它们中的每一个发
- ClientA和ClientB都连接到服务器
- ClientA登录(使用类似“登录用户名密码”的命令)
- ClientB也会登录,但使用与ClientA相同的用户名和密码
- ClientA应强制注销,而ClientB应成功登录
连接
是当前的客户端-服务器连接。对于每个成功登录的连接,我将用户名存储在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();
}
}
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;
ClientThread.java内部的登录案例
public class Main {
public static void main(String[] args) throws IOException {
ClientThread clientThread = new ClientThread();
clientThread.start();
}
}
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将不会收到其消息。正确的方法是什么?非常感谢 如果您的问题是为什么clientA没有收到“我们将让您注销”消息,我建议您在发送消息之前检查clientA是否仍然连接。请提供帮助以帮助其他人进一步调查。对此,我深表歉意!我用Node和Java中的相关代码更新了这篇文章。