例如,我有一个房间
public class Room {
private int id;
private Set<User> users;
}
所以我希望它成为我的websocket应用程序的端点。但可能有很多房间,我希望每个房间都有自己的URI(例如,房间/1、房间/2等)
显然,@ServerEnpoint annotaion只允许常量。那么,有什么办法可以做到吗?
类似这样的东西:
@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 )
只向特定房间号码/客户发送消息:
// 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)) {
...
当客户端断开连接时:
@OnClose
public void onConnectionClose(Session session) {
openSessions.remove(session.getId());
}
您可以使用此per函数在同一控制器中映射具有不同变量的请求
@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