Issue with netty websocket headers name in lowercase

允我心安 提交于 2020-06-17 09:18:06

问题


I am using netty to implement a websocket server. The server needs to work with some old websocket clients libraries (written in other languages) out there which does not honour the HTTP header case insensitivity rule. I am facing a problem there.

My inbound channel pipeline is pretty standard which looks like following HttpServerCodec -> HttpObjectAggregator -> HttpRequestBuilder ->WebSocketServerProtocolHandler -> WebSocketFrameAggregator -> CustomHandler

In netty version 4.1.23.Final I see that the websocket handshake response being sent to client is all in lowercase header names, like following.

upgrade: websocket\r\n
connection: upgrade\r\n
sec-websocket-accept: hex-values=\r\n

But the older websocket client expects the header in the following format.

Upgrade: websocket\r\n
Connection: Upgrade\r\n
Sec-WebSocket-Accept: hex-values=\r\n

As a result the websocket connection does not complete. Has anybody faced this problem?

The header strings are coming from HttpHeaderNames class instead of HttpHeader class. The fix is to change WebSocketServerHandshaker13.newHandshakeResponse() to use the required HttpHeader. But that would need change in netty code itself probably . Can somebody suggest any cleaner way to get around this problem without changing netty code?

  1. Is there anyway to add/modify http response header while using the existing netty websocket handshaker classes?
  2. Should I write custom WebSocketServerProtocolHandler to achieve the same?
  3. Any other way?

Appreciate any response!!!

Thanks much in advance.


回答1:


The only way is to implement it yourself sadly as this is definitely a "broken" behaviour on the client side. What you could do is to add a ChannelOutboundHandler to the ChannelPipeline which will "fix-up" the headers for you.




回答2:


You can use Netty ChannelOutboundHandlerAdapter to change the header somewhere in the pipeline. After that remote that handler from the pipeline so it will not interfere with WebSocket frames. Please find the code below.

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.HttpResponse;

public class OutboundHeadersChanger extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (msg instanceof HttpResponse) {
            ((HttpResponse) msg).headers().set("some-header", "some-header-value");
        }

        super.write(ctx, msg, promise);
    }
}


来源:https://stackoverflow.com/questions/50477233/issue-with-netty-websocket-headers-name-in-lowercase

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!