我可以将websocket端点映射到一个静态上下文或带有uri变量的上下文:@ServerEndpoint("/{name}")
,它将匹配/任何但不匹配/任何/东西。如何映射@ServerEndpoint
以匹配/ any / random / uri,如@WebServlet(/*)
?
答案 0 :(得分:1)
我使用此解决方案
JavaScript部分:
<script type="text/javascript">
if (window.WebSocket) {
var ws = new WebSocket("ws://localhost:8080/rooms/" + "room number or what ever");
ws.onopen = function () {
console.log('Connected');
};
ws.onmessage = function (event) {
var text = event.data;
console.log(text);
};
}
else {
// Bad luck. Browser doesn't support it.
}
</script>
Java类:
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@ServerEndpoint(value = "/rooms/{roomnumber}")
public class WebSocketEndPoint implements Serializable {
private static final long serialVersionUID = 1L;
private static final Map<String, Session> sessions = Collections.synchronizedMap(new HashMap<String, Session>());
public static void sendAll(String text, String roomNumber) {
synchronized (sessions) {
for (Map.Entry<String, Session> entry : sessions.entrySet()) {
Session s = entry.getValue();
if (s.isOpen() && s.getUserProperties().get("roomnumber").equals(roomNumber)) {
entry.getValue().getAsyncRemote().sendText(text);
}
}
}
}
@OnOpen
public void onConnectionOpen(final Session session, @PathParam("roomnumber") final String roomnumber) {
session.getUserProperties().put("roomnumber", roomnumber);
sessions.put(String.valueOf(session.getId()), session);
}
@OnClose
public void onClose(Session session) {
sessions.remove(session.getId());
}
}
如果您有很多连接,我建议使用不同的方式来过滤会话(与周期条件不同)