注入变量到 websocket 注释 @ServerEndpoint("/myVar")

Injection variable to websocket annotation @ServerEndpoint("/myVar")

我有聊天映射到静态 URL。我需要获得为用户创建房间的机会。

当应用程序已经 运行 时,如何在注解 @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。

帮我创建注解的实现变量注入。谢谢。

我认为如果您只想创建和处理聊天室,则不需要任何注入。您只需要通过 java 独立于端点的代码来处理此问题。

我推荐你:

  • 创建一个 websocket 服务器端点:@ServerEndpoint("/chat"/{client_id})。此客户端 ID pathParam 可用作会话 ID。
  • 在 ChatEndpoint class 中,初始化一个房间列表(这个列表应该 static <=> 在所有线程之间通用)。
  • 创建您的业务方法来处理客户和房间(create/delete 用户、create/delete 房间、订阅房间...等)。
  • 最后,在您的聊天消息中尝试指定房间目的地。如果您使用 JSON 格式,这会非常简单。

message = { ... ,"room": "room1", ... }