Websocket Pathparam验证

时间:2018-11-21 04:30:04

标签: java websocket

我尝试在服务器端应用websocket以接收来自不同客户端的信息。websocket端点使用pathparam来标识特定的约束。

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

}

在此步骤之前,代码运行良好,并且我可以接收来自不同客户端的消息并基于pathparam标识设备。

但是,如果设备ID无效,我想发送404响应以使升级握手失败。应当在@OnOpen之前发送404响应,并且我已经检查了配置程序,其中仅包含五个功能:

  • getEndpointInstance
  • getNegotiatedSubprotocol
  • getNegotiatedExtensions
  • checkOrigin
  • modifyHandshake

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

我也应该应用@WebFilter吗?还是@ServerEndPoint中有任何常用方法?

1 个答案:

答案 0 :(得分:0)

我最终尝试在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()
    }
}