Rahul
Rahul

Reputation: 1807

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?

Upvotes: 5

Views: 4225

Answers (2)

sinclair
sinclair

Reputation: 2861

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

Upvotes: 5

Carlos Bribiescas
Carlos Bribiescas

Reputation: 4407

You can use this per function to map requests with different variables in the same controller

@RequestMapping(value = "/endpoint/{endpointVariable}", method = RequestMethod.GET)
public ReturnDTO getReturnDTO(<params>){
    // Here the variable, endpointVariable, will be accessible
    // In my experiences its always been an integer, but I'm sure a string
    // would be possible.  check with debugger
}

http://www.journaldev.com/3358/spring-mvc-requestmapping-annotation-example-with-controller-methods-headers-params-requestparam-pathvariable

Upvotes: -2

Related Questions