这里有一种“noob”问题。
我有一个小应用程序要写(就像一个简单的游戏)。有服务器端和客户端。它必须使用websockets作为通信方式。 Server有一个服务器类(使用main()启动服务器)以及服务器端点类。但是,游戏不是基于转向,而是基于实时。因此服务器必须在动态字段的每个“tick”b / c进行某些计算。 我假设Threads在这种情况下很适合,但我不知道如何将线程放在这种服务器上。
正如我所看到的,唯一可以接收/发送消息的是端点。如果我让它实现Runnable并且每0.5秒暂停一次,它将不会在该暂停时间内接受消息。如果我为此目的定义了一个不同的类,我不知道如何在端点内部启动它并为它们进行通信。 有没有人有任何建议/信息/链接/任何可能有帮助的事情?
提前谢谢。
答案 0 :(得分:0)
服务器端点将持续从客户端接收数据。您所要做的就是在其他线程中处理该数据。您可以为此目的定义一个不同的类(一个线程)。该线程类将有两个不同的队列。
在队列中 - 从端点接收数据
Out queue - 将数据发送到端点 (您可以使用ConcurrentLinkedQueue。更多帮助 - > How to use ConcurrentLinkedQueue?)
在端点内启动此处理线程。当端点接收数据时,将它们放入In Queue。持续监听Out Queue并将该数据再次发送到客户端。
端点代码
@OnMessage
public void onMessage(String message,Session peer) throws IOException{
processingThread t = new processThread(peer);
t.inQueue.add(data);
t.start();
String s;
//listen to the Out Queue
while (true) {
while ((s =t.outQueue.poll()) != null) {
peer.getBasicRemote.sendText(dataToBeSent);
}
}
}
processingThread Code
public class processingThread extends Thread{
public ConcurrentLinkedQueue<String> inQueue = new ConcurrentLinkedQueue<String>();
public ConcurrentLinkedQueue<String> outQueue = new ConcurrentLinkedQueue<String>();
public void run(){
//listen to in queue and process
//after processing put to the out queue
}
}
希望这会有所帮助:)