使用modifyHandshake在WebSocket握手上添加标头

时间:2014-05-17 18:24:12

标签: java websocket jetty jsr356

我试图在握手期间发送自定义标头。我可以拦截与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|._.@..Fp..G....c..0...].D...F.H...{E-.k{.pP...S{n...

我想将生成的ID发送给客户端,并且不想在额外的呼叫中执行此操作。有没有理由不发送或有不同的方法?

我在dev blog上找到了一个示例,它还在modifyHandshake中添加了一个标题,所以我从理论上说它应该是可能的。

1 个答案:

答案 0 :(得分:3)

我认为这是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