使用Java" JSR 356 - Java API for WebSocket"的Tyrus参考实现,我找不到一种方法来访问用于Websocket升级的HTTP连接。因此,我无法访问浏览器发送的HTTP标头。
有没有办法读取HTTP UserAgent标头?
投射"会话"反对" TyrusSession"或类似的是可以接受的,我必须这样做以获得远程地址。再次将UserAgent作为Websocket连接内的消息发送将是我的后备解决方案。
答案 0 :(得分:0)
警告:ServerEndpointConfig在所有端点实例之间共享,并且可以同时完成多个升级请求!见评论!
端点获取配置程序:
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value = "/foo", configurator = MyServerEndpointConfigurator.class)
public class MyEndpoint {
@OnOpen
public void onOpen(Session session, EndpointConfig endpointConfig) throws Exception {
String ip = ((TyrusSession) session).getRemoteAddr();
String userAgent = (String) endpointConfig.getUserProperties().get("user-agent");
...
}
}
配置程序如下所示:
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
public class MyServerEndpointConfigurator extends ServerEndpointConfig.Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
if (request.getHeaders().containsKey("user-agent")) {
sec.getUserProperties().put("user-agent", request.getHeaders().get("user-agent").get(0)); // lower-case!
}
}
}