建立websocket会话后发送标题/正文

时间:2015-01-07 14:16:06

标签: session websocket spring-websocket

我使用org.eclipse.jetty.websocket.client.WebSocketClient建立websocket连接。 在初始握手(协议切换/升级)之后,建立了websocket会话。

以下是我正在使用的代码:

WebSocketClient client = new WebSocketClient();
client.start();
URI echoUri = new URI("destinationURI");
ClientUpgradeRequest request = new ClientUpgradeRequest();      
request.setHeader("myCustomHeader", "CustomHeader");    
client.connect(socket, echoUri, request);

Collection<WebSocketSession> sessions = client.getConnectionManager().getSessions();
for (WebSocketSession webSocketSession : sessions) {
    webSocketSession.getRemote().sendString("<Custome message>");//I am able to recieve the messages //to the configured message handler
}

我的留言处理程序如下:

@Override
    protected void handleTextMessage(WebSocketSession session,
            TextMessage message//This is what i sent above) throws Exception {
        session.getHandshakeHeaders();//This has "myCustomHeader", "CustomHeader"
        BinaryMessage binaryMessage = new BinaryMessage(new String(
                "Hello . This is message sent from server").getBytes());
        session.sendMessage(binaryMessage);
    }

在建立Web套接字会话后,是否可以发送自定义标头?

这是我试过的:

WebSocketClient client = new WebSocketClient();
client.start();
URI echoUri = new URI("destinationURI");
ClientUpgradeRequest request = new ClientUpgradeRequest();      
request.setHeader("myCustomHeader", "CustomHeader");    
client.connect(socket, echoUri, request);
Collection<WebSocketSession> sessions = client.getConnectionManager().getSessions();
for (WebSocketSession webSocketSession : sessions) {
    webSocketSession.getUpgradeRequest().setHeader("mySecondCustomHeader","MySecondCustomHeader");
    webSocketSession.getRemote().sendString("<Custome message>");//I am able to recieve the messages //to the configured message handler
}

我只在session.getHandshakeHeaders()中获取myCustomHeader而不是mySecondCustomHeader

@Override
    protected void handleTextMessage(WebSocketSession session,
            TextMessage message//This is what i sent above) throws Exception {
        session.getHandshakeHeaders();//This has "myCustomHeader", "CustomHeader"
        BinaryMessage binaryMessage = new BinaryMessage(new String(
                "Hello . This is message sent from server").getBytes());
        session.sendMessage(binaryMessage);
    }

1 个答案:

答案 0 :(得分:2)

  

可以在Web套接字会话之后发送自定义标头   成立?

不,这是不可能的。一旦HTTP协商结束,连接只使用二进制帧进行通信,不能进行更多的HTTP交互。