netty实现websocket通信

调用注意:

1、端口一定要是可以访问的。

2、依赖必须注意和其他版本冲突,比如redis的springboot starter包,会与5.0+版本冲突。

 <netty.version>4.1.74.Final</netty.version>            
<dependency>
     <groupId>io.netty</groupId>
     <artifactId>netty-all</artifactId>
     <version>${netty.version}</version>
</dependency>

首先创建socket服务


@Component
@Slf4j
public class NettyWebSocketServer extends Thread {

    public static String MsgCode = "GBK";

    public Integer port=8099;



    @Override
    public void run() {
        startServer();
    }

    private void startServer() {
        EventLoopGroup bossGroup = null;
        EventLoopGroup workGroup = null;
        ServerBootstrap serverBootstrap = null;
        ChannelFuture future = null;
        try {
            //初始化线程组
            bossGroup = new NioEventLoopGroup();
            workGroup = new NioEventLoopGroup();
            //初始化服务端配置
            serverBootstrap = new ServerBootstrap();
            //绑定线程组
            serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new WebSocketChannelInitializer());
            future = serverBootstrap.bind(new InetSocketAddress(port)).sync();
            log.info(" *************Web Socket服务端启动成功 Port:{}*********** ", port);
        } catch (Exception e) {
            log.error("Web Socket服务端启动异常", e);
        } finally {
            if (future != null) {
                try {
                    future.channel().closeFuture().sync();
                } catch (InterruptedException e) {
                    log.error("channel关闭异常:", e);
                }
            }
            if (bossGroup != null) {
                //线程组资源回收
                bossGroup.shutdownGracefully();
            }

            if (workGroup != null) {
                //线程组资源回收
                workGroup.shutdownGracefully();
            }


        }
    }

}

创建WebSocketChannelInitializer,配置请求目录、handle类,以及请求的最大内容

public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(5000));
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast(new TextWebSocketFrameHandle());
    }
}

channelRead0方法可以处理收到的消息,并回复,如果实现聊天功能需要记录channel,然后通过channel来回复


@Slf4j
public class TextWebSocketFrameHandle extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        log.info("收到消息:" + msg.text());
        ctx.channel().writeAndFlush(new TextWebSocketFrame("收到客户端消息"));
    }

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

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("handlerAdded:" +ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("异常发生");
        ctx.close();
    }
}

web调用的地址为:ws://localhost:8099/ws

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值