gpt4 book ai didi

java - 将 @ServerEndpoint ("/{path:.+}")映射到任何路径?

转载 作者:行者123 更新时间:2023-11-30 07:39:45 26 4
gpt4 key购买 nike

我可以将 websocket 端点映射到一组静态上下文或带有 uri 变量的上下文:@ServerEndpoint("/{name}") 它将匹配/anything 但不匹配/any/thing。如何映射 @ServerEndpoint 使其与/any/random/uri 像 @WebServlet(/*) 一样匹配?

最佳答案

我使用这个解决方案

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

}

如果您有很多连接,我建议使用不同的方式来过滤 session (与周期条件不同)

关于java - 将 @ServerEndpoint ("/{path:.+}")映射到任何路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34849471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com