我有映射到静态 URL 的聊天。我需要有机会为用户创建房间。
当应用程序已经运行时,如何在注释中注入(inject)变量@ServerEndpoint("/myVariable")
?
class SomeClass{
public void createRoom(User user) {
String name = user.getName();
//...Somehow inject name to annotation @ServerEndpoint("/name")...
}
}
@ServerEndpoint("/chat") //May be replace to @ServerEndpoint(someGetteUserName())
public class ChatEndpoint {
@OnMessage
public void message(String message, Session client)
throws IOException, EncodeException {
for (Session peer : client.getOpenSessions()) {
peer.getBasicRemote().sendText(message);
}
}
}
我不使用 Spring,这是透明的 websocket 和 Glassfish。
帮助我创建注释的实现变量注入(inject)。谢谢。
最佳答案
我认为如果您只想创建和处理聊天室,则不需要任何注入(inject)。您只需通过独立于端点的 java 代码来处理此问题。
我建议您:
- 创建一个 WebSocket 服务器端点:
@ServerEndpoint("/chat"/{client_id})
。该客户端 ID pathParam 可以用作 session ID。 - 在 ChatEndpoint 类中,初始化房间列表(此列表应该是
静态
<=>在所有线程之间通用)。 - 创建您的业务方法来处理客户和聊天室(创建/删除用户、创建/删除聊天室、订阅聊天室等)。
- 最后,请尝试在聊天消息中指定房间目的地。如果您使用 JSON 格式,这会非常简单。
message = { ... ,"room": "room1", ... }
关于java - 将变量注入(inject)到 websocket 注解 @ServerEndpoint ("/myVar"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44908332/