Search code examples
javawebsocketjava-websocket

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


I have chat which mapping to static URL. I need get the opportunity creating rooms for user.

How to inject variable in annotation @ServerEndpoint("/myVariable") when app already running?

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);
        }
    }
}

I don't use Spring this is clear websocket and Glassfish.

Help me create implementation variable injection to annotation. Thank You.


Solution

  • I think that you don't need any injection if you only want to create and handle chat rooms. You just need to handle this by java code independently from your endpoint.

    I recommend you to:

    • Create one websocket server endpoint: @ServerEndpoint("/chat"/{client_id}). This client id pathParam is may serve as a session id.
    • In ChatEndpoint class, initialize a list of rooms (this list should be static <=> common between all threads).
    • Create your business methods to handle clients and rooms(create/delete user, create/delete room, subscribe to a room...etc).
    • Finally, in your chat message try to specify the room destination. This can be very simple if you use JSON format.

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