Vladimir
Vladimir

Reputation: 214

Netty 4.x.x WebSocket handshake for streaming server

I have a Echo server example from Official Netty Echo Server

How to add ability to connect and streaming to it from websocket?

here is my ServerHandler code:

public class ServerHandler extends ChannelInboundHandlerAdapter
{
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        // !!!!! Think here should be WebSocket Handshake?
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
    {
        System.out.println(msg);
        ctx.write(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx)
    {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
    {
          // Close the connection when an exception is raised.
        cause.printStackTrace();
    }
}

Right now Chrome connection says: WebSocket connection to 'ws://127.0.0.1:8080/' failed: Error during WebSocket handshake: Invalid status line

Upvotes: 2

Views: 2434

Answers (2)

Vladimir
Vladimir

Reputation: 214

So, I found solution! It is not compliant to native documentation of web-socket, but who cares it works as I expected!

public void channelRead(ChannelHandlerContext ctx, Object msg)
    {
        DefaultHttpRequest httpRequest = null;
        if (msg instanceof DefaultHttpRequest)
        {
            httpRequest = (DefaultHttpRequest) msg;

            // Handshake
            WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory("ws://127.0.0.1:8080/", null, false);
            final Channel channel = ctx.channel();
            final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(httpRequest);

            if (handshaker == null) {

            } else {
                ChannelFuture handshake = handshaker.handshake(channel, httpRequest);
            }
        }
    }

Do not forget to add

p.addLast(new HttpRequestDecoder(4096, 8192, 8192, false));
p.addLast(new HttpResponseEncoder());

to your pipeline.

Upvotes: 0

Nicholas
Nicholas

Reputation: 16056

Netty servers do not automatically handle all protocols, so you would need to add support for WebSockets.

I find the best place to start is to examine the relevant examples in Netty's xref page. Scroll down the package list until you get to the io.netty.example packages. In that list you will find a package called io.netty.example.http.websocketx.server. There is a fairly simple and well laid out example on how to implement a websocket server, or just the handler.

Websocket servers are slightly more complicated than other servers in that they must start life as an HTTP server because the protocol specifies that websockets must be initiated by "upgrading" an HTTP connection, but as I said, the example referenced above makes this fairly clear.

Upvotes: 1

Related Questions