Java 杂谈

【第4篇】Netty对WebSocket的支援分析

2019-05-13  本文已影响0人  爱学习的蹭蹭

1、WebSocket的简要描述(重点)

2、Netty对WebSocket的支援(重点)

4、Netty的重要的类

HttpObjectAggregator ChuckedWriteHandler
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(8192));
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));

        pipeline.addLast(new TextWebSocketFrameHandler());
    }
}

3、WebSocket处理要点


public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("收到消息: " + msg.text());

        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间: " + LocalDateTime.now()));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerAdded: " + ctx.channel().id().asLongText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerRemoved: " + ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常发生");
        ctx.close();
    }
}
public interface ChannelId extends Serializable, Comparable<ChannelId> {
    /**
     * 返回简短,但全局非惟一的字符串表示形式。
     */
    String asShortText();

    /**
     * 返回长,但全局唯一的字符串表示形式。
     */
    String asLongText();
}

WebSocketServerProtocolHandler
上一篇下一篇

猜你喜欢

热点阅读