我正在尝试在握手期间发送自定义标头。我可以使用ServerEndpointConfig.Configurator拦截握手,并覆盖ModifyHandshake。
public class WebsocketConfigurator extends ServerEndpointConfig.Configurator {
public static final String HEADER_SOCKET_ID = "X-Socket-Id";
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
String id = UUID.randomUUID().toString();
List<String> list = new ArrayList<String>();
list.add(id);
response.getHeaders().put(HEADER_SOCKET_ID, list);
sec.getUserProperties().put(HEADER_SOCKET_ID, id); }
}
该方法被调用,并且id被添加到响应头中,尽管它不发送其他头。
我用wireshark嗅探了一下,以确保它不是客户端框架:
GET /websocket HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:8080
Origin: http://localhost:8080
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: QgZwJwVv8+i/vaKFHDqPZg==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits, x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36
HTTP/1.1 101 Switching Protocols
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: Kim6Qjj7sOBLfG+6I++gS/OVx4A=
Sec-WebSocket-Extensions: permessage-deflate
.u.....0....y.R...K'6...9M
.....PU.......}..).B..g.P....D..4."!..R|[email protected]...].D...F.H...{E-.k{.pP...S{n...
我想将生成的ID发送给客户端,并且不想在额外的呼叫中进行。是否有原因不发送或有其他方法?
我在dev blog上找到了一个示例,该示例还在
modifyHandshake
中添加了标头,因此我认为从理论上讲应该是可能的。 最佳答案
我认为这是Jetty实施Websockets中的错误。我在用
Jetty: 9.1.1.v20140108
我简要地看了一下代码,在我看来,在发送响应之后,他们叫了ModifyHandshake。虽然也可能是完全错误的。
但是升级到
Jetty: 9.2.0.RC0
解决此问题。
GET /websocket HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:8080
Origin: http://localhost:8080
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: P93FwyXNrD9ecVHCDywzTg==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits, x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.8 Safari/537.36
HTTP/1.1 101 Switching Protocols
Date: Tue, 20 May 2014 10:58:31 GMT
Connection: Upgrade
Sec-WebSocket-Accept: U+tHV5zYWWSX8vDsVdiDo7yUN9s=
Upgrade: WebSocket
X-Socket-Id: f16bc17b-9a5c-45a4-a851-9d66ffb1d2f1