官网英文参考:
中文解析:
Websocket 提供的Java API 是你能够通过配置类控制server endpoint的实例化方式,你可以自定义endpoint 配置逻辑完成下面的工作:
1. 访问Websocket 连接HTTP请求详情。
2. 执行自定义检查HTTP原始请求头(Perform custom checks on the Origin HTTP header)
3. 修改Websocket 握手回复
4. 从客户端连接中获取Websocket 子协议
5. 控制endpoint 初始化和实例化
为了提供自定义endpoint 配置逻辑,需要写一个类继承ServerEndPointConfig.Configrator,然后重写他的方法,最后将其配置为serverEndPoint 中参数configurator 的值。
下面是一个利用Configurator 类,使得握手请求的对象头在endpoint实例中是可用的(For example, the following configurator class makes the handshake request object available to endpoint instances:)。
public class CustomConfigurator extends ServerEndpointConfig.Configurator { @Override public void modifyHandshake(ServerEndpointConfig conf, HandshakeRequest req, HandshakeResponse resp) { conf.getUserProperties().put("handshakereq", req); } }
The following endpoint class configures endpoint instances with the custom configurator, which enables them to access the handshake request object:
通过自定义配置类,使得实例化中可以访问握手协议请求头。
@ServerEndpoint( value = "/myendpoint", configurator = CustomConfigurator.class ) public class MyEndpoint { @OnOpen public void open(Session s, EndpointConfig conf) { HandshakeRequest req = (HandshakeRequest) conf.getUserProperties() .get("handshakereq"); Map<String,List<String>> headers = req.getHeaders(); ... }
}
endpoint类能够使用握手请求头,访问详细的HTTP请求头,如HttpSession请求对象。
更多的endpoint 配置,可以参考 API中ServerEndpointConfig.Configurator