Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way creating dynamic @ServerEndpoint address in Java?

For example, I have a room

public class Room {
   private int id;
   private Set<User> users;
}

So I want it to be endpoint for my websocket application. But there may be a lot of rooms and I want each of them could have own URI (for example, rooms/1, rooms/2 etc.)

Evidently, @ServerEnpoint annotaion allows only constants. So, is there any way to make it?

like image 293
Rahul Avatar asked Oct 19 '22 22:10

Rahul


1 Answers

Something like this:

@ServerEndpoint(value = "/rooms/{roomnumber}")
public class....

static Map<String, Session> openSessions = ...
@OnOpen
public void onConnectionOpen(final Session session, @PathParam("roomnumber") final String roomnumber, 
...
   //store roomnumber in session
   session.getUserProperties().put("roomnumber", roomnumber);
   openSessions.put( String.valueOf(session.getId()), session ) 

To only send messages to specific roomnumbers/clients:

// check if session corresponds to the roomnumber 
  for (Map.Entry<String, Session> entry : openSessions.entrySet()) {

    Session s = entry.getValue();
    if (s.isOpen() && s.getUserProperties().get("roomnumber").equals(roomnumber_you_want_to_address)) {
  ... 

And when a client disconnects:

 @OnClose
public void onConnectionClose(Session session) {
    openSessions.remove(session.getId());
}
like image 68
sinclair Avatar answered Nov 02 '22 05:11

sinclair