在服务器-客户端结构中向特定客户端发送消息的正确方式是什么?



我正在构建这个程序,其中服务器向不同的客户端发送不同的订单。程序的一部分将订单发送到服务器,服务器处理消息发送到哪个客户端,然后将消息发送到它应该发送的特定客户端。

下面是发送消息的代码:

@Override
public void run() {
boolean active = true;
String oldMsgToDron = "";
String to_print = "";
BufferedWriter bw = new BufferedWriter(osw);
while(active) {
try {
//msgToDron is declared in DronController as: public static volatile String msgToDron;
to_print = DronController.msgToDron;
if(to_print.equals(oldMsgToDron) == false) {

System.out.println("Message we are sending to the dron: " + to_print);

if(to_print.length()>45 && to_print.startsWith("!whisper") && dronId.equals(to_print.substring(9, 45))) {
bw.write("Server whispers:" + to_print.replace("!whisper " + dronId, ""));
bw.newLine();
bw.flush();
System.out.println("Message we sent to the dron: " + to_print);
}

else if (to_print.startsWith("!whisper") == false){
bw.write(to_print);
bw.newLine();
bw.flush();
System.out.println("A message for all drones has been sent.");
}
try{Thread.sleep(5);}catch(InterruptedException ex){ex.printStackTrace();}
oldMsgToDron = "";
to_print = "";
DronController.msgToDronEsclavo = "";
}
}catch(IOException e) {
try {
active = false;
if(bw != null) 
bw.close();
}catch(IOException f) {e.printStackTrace();f.printStackTrace();break;}
}           
}
}

我的问题是消息是在控制客户端连接的线程内部处理的,并且在循环结束时消息被更改为空字符串。这样我就可以连续两次发送相同的订单,而服务器不会一直向客户端发送相同的消息。

事情是这样做,如果我有3个或更多的连接,它开始给我的问题,因为每当其中一个线程到达终点,他们把变量DronController.msgToDronEsclavo,to_printoldMsgToDron空字符串之前,其他线程有时间检查消息是否为客户端,他们已经分配。

如何避免不同的线程在其他线程完成之前更改变量?这种结构有什么设计模式吗?这类项目有哪些好的实践?

另外,我想过让客户端检查发送的消息是否适合他们,但我发现这种解决方案不安全。

通常是客户端通过网络连接到服务器-请求数据或发送数据。服务器没有可靠的方法来知道客户端下次何时连接,或者自己触发连接。

如果你想从服务器发送数据到客户端,过去的模式是客户端轮询数据,或者总是有一个请求等待来自服务器的下一个数据包。你可能想阅读AJAX和Websocket

另一种模式是安装一个webhook,它本质上是给服务器一个客户端可以访问的URL。这实际上是将服务器作为客户端,而客户端作为服务器进行数据传输。

好吧,上面写的是关于你的问题标题。现在看看内容,你会问如何防止线程相互影响。

学习Java线程同步的概念。这是一个很好的教程。

最新更新