在使用@ServerEndpoint注解的WebSocket服务器端点中,无法直接携带参数。但是,可以通过以下方法解决这个问题:

  1. 将参数作为查询字符串传递。例如:ws://localhost:8080/websocket?param1=value1&param2=value2

  2. 在WebSocket连接建立后使用WebSocketSession的getQueryString()方法获取查询字符串,然后解析参数。

  3. 将参数存储在HttpSession中,然后在WebSocket连接建立时从HttpSession中获取参数。

例如,以下代码演示了如何从HttpSession中获取参数:

@ServerEndpoint("/websocket")
public class MyWebSocket {

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        String param1 = (String) httpSession.getAttribute("param1");
        String param2 = (String) httpSession.getAttribute("param2");
        // do something with the parameters
    }

    // other WebSocket methods
}

在使用WebSocket时,需要在建立连接之前将参数存储在HttpSession中:

HttpSession httpSession = request.getSession();
httpSession.setAttribute("param1", "value1");
httpSession.setAttribute("param2", "value2");
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(MyWebSocket.class, URI.create("ws://localhost:8080/websocket"));
``
websocket ServerEndpoint 携带参数不生效

原文地址: https://www.cveoy.top/t/topic/cpEP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录