java - 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 之前发送,我检查了配置器,只包含五个函数:
- 获取端点实例
- 获取协商子协议
- getNegotiatedExtensions
- 检查原点
- 修改握手
在升级握手之前,所有功能似乎都无法处理验证,但我找不到任何通用方法。
我还应该申请@WebFilter 吗?或者@ServerEndPoint 中是否有任何常用方法?
解决方案
我尝试最终处理验证,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()
}
}
推荐阅读
- amazon-web-services - 如何在 AWS CDK 中导入现有 CloudTrail
- azure - 即使下载了发布配置文件,Web 部署到 Azure 也停止工作
- django - 如何处理来自通过自定义模板标签加载的 Django 表单的 POST 请求?
- linux - fetchmail 警告 imap.gmail.com 服务器证书
- c# - 哪个属性或方法在 ASP.Net Core MVC 2.2 中返回活动/关闭/进行中状态的连接数
- ios - 导入的分发证书未显示在钥匙串访问中
- ssh - 在远程会话中使用 tmux 选择鼠标后复制到客户端剪贴板
- c++ - 如果方法用作 constexpr,则切换实现?
- flutter - 如何在颤振中不生成红框,android studio,
- java - 我得到一个空指针异常,我不知道为什么,你能帮帮我吗?爪哇