美文网首页
java WebSocket客户端基于Netty代码实现

java WebSocket客户端基于Netty代码实现

作者: SuperEngCoding | 来源:发表于2019-03-11 10:18 被阅读0次

    背景

    • 最近接了一个任务对接WS的服务端,从网上找了一些案例,都不能实际的去用到工作当中,根据自己的摸索写了以下代码完成了对接工作,话不多说直接上代码。

    客户端代码

    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
            try {
                URI uri = new URI("ws://192.168.50.xx:xx/xx/xx");
                Bootstrap bootstrap = new Bootstrap();
                MockClientHandler webSocketClientHandler = new MockClientHandler(
                        WebSocketClientHandshakerFactory.newHandshaker(uri
                                , WebSocketVersion.V13
                                , null
                                , false
                                , new DefaultHttpHeaders()));
                bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).
                        handler(new MockClientInitializer(webSocketClientHandler));
                Channel channel = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel();
                channel.closeFuture().sync();
            } catch (InterruptedException | URISyntaxException e) {
                log.error("socket连接异常:{}",e);
                e.printStackTrace();
            } finally {
                eventLoopGroup.shutdownGracefully();
            }
    

    初始化通道

    public class MockClientInitializer extends ChannelInitializer<SocketChannel> {
        private MockClientHandler mockClientHandler;
    
        MockClientInitializer(MockClientHandler mockClientHandler) {
            this.mockClientHandler = mockClientHandler;
        }
    
        @Override
        protected void initChannel(SocketChannel channel)  {
            ChannelPipeline pipeline = channel.pipeline();
            // 将请求与应答消息编码或者解码为HTTP消息
            pipeline.addLast(new HttpClientCodec());
            pipeline.addLast(new LoggingHandler(LogLevel.INFO));
            pipeline.addLast("decoder", new StringDecoder());
            pipeline.addLast("encoder", new StringEncoder());
            // 客户端Handler
            pipeline.addLast("handler", mockClientHandler);
        }
    }
    

    消息处理类

    @Slf4j
    public class MockClientHandler extends SimpleChannelInboundHandler<String> {
    
        private MsgHandleService msgHandleService;
    
        private final WebSocketClientHandshaker webSocketClientHandshaker;
    
        public MockClientHandler(WebSocketClientHandshaker webSocketClientHandshaker) {
            this.webSocketClientHandshaker = webSocketClientHandshaker;
            this.msgHandleService = SpringContextHolder.getBean(MsgHandleService.class);
        }
    
        /**
         * 当客户端主动链接服务端的链接后,调用此方法
         *
         * @param channelHandlerContext ChannelHandlerContext
         */
        @Override
        public void channelActive(ChannelHandlerContext channelHandlerContext) {
            log.info("\n\t⌜⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓\n" +
                    "\t├ [Mock 建立连接]\n" +
                    "\t⌞⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓");
    
            Channel channel = channelHandlerContext.channel();
            // 握手
            webSocketClientHandshaker.handshake(channel);
        }
    
    
        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, String data) {
            log.info("接收到客户端的响应为:{}", data);
           //自定义处理消息
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            log.info("\n\t⌜⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓\n" +
                    "\t├ [exception]: {}\n" +
                    "\t⌞⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓", cause.getMessage());
            ctx.close();
        }
    
        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) {
            System.out.println("与服务器端断开连接");
        }
    
        @Override
        public void channelReadComplete(ChannelHandlerContext channelHandlerContext) {
            channelHandlerContext.flush();
        }
    
    

    总结

    • 到此代码已经完毕,希望能够帮忙各位小伙伴。

    相关文章

      网友评论

          本文标题:java WebSocket客户端基于Netty代码实现

          本文链接:https://www.haomeiwen.com/subject/hnlvpqtx.html