我使用 javax-inject 中的 websockets 和 Singleton 制作了一个应用程序。然而,对于每个新的 websocket session ,都会创建新的 HashMap 。我应该怎么做才能为所有 session 创建相互映射?
import javax.inject.Singleton;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@ServerEndpoint(value = "/game_endpoint")
@Singleton
public class WaterWorldGame {
Map<Session, Player> players = new HashMap<>();
...
}
javax-inject 中是否有任何注释,或者使用 Spring 制作会更容易吗?
最佳答案
我认为容器为每个客户端创建端点的新实例,这就是创建新 HashMap 的原因。
您可以将端点类和单例分开。
@Singleton
public class WaterWorldGame {
Map<Session, Player> players = new HashMap<>();
// getter, setter
}
@ServerEndpoint(value = "/game_endpoint")
public class GameEndpoint{
@EJB
WaterWorldGame game;
}
关于java - 如何为服务器端的每个 websocket session 创建相互映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31149947/