首页 > 解决方案 > Websocket 路径参数验证

问题描述

我尝试在服务器端应用 websockets 以接收来自不同客户端的信息 websocket Endpoint 使用路径参数来识别特定的客户端。

ws://192.168.1.100:8080/listener/device_00001

终点类是:

@ServerEndpoint(
   value = "/listener/{deviceid}",
   configurator = WsConfig.class,
   subprotocols = {"abcProtocolv1", "abcProtocolv2"}
)
public class WsServer {

   @OnOpen
   public void onOpen(final Session session, @PathParam("deviceid") final String id) {
      //some handling method
   }

   @OnClose
   //some code here

   @OnMessage
   //some code here

}

在这一步之前代码运行良好,我可以接收来自不同客户端的消息并根据路径参数识别设备。

但是,如果设备 ID 无效,我想发送 404 响应以使升级握手失败。404 响应应该在@OnOpen 之前发送,我检查了配置器,只包含五个函数:

在升级握手之前,所有功能似乎都无法处理验证,但我找不到任何通用方法。

我还应该申请@WebFilter 吗?或者@ServerEndPoint 中是否有任何常用方法?

标签: javawebsocket

解决方案


我尝试最终处理验证,modifyHandshake但它不应该是一种常见的方法。

modifyHandshake中,@PathParam变量可以在 中找到request.getParameterMap()

@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
    String deviceId = request.getParameterMap().get("deviceid").get(0);
    if (isDeviceValid(deviceId)) {
       //Some code here and 101 is kept 
    } else {
       //Use java reflection to modify the http status and then clear the header 
       //The reflection code is depended on your Http Handler type
       response.getHeaders().clear()
    }
}

推荐阅读