NettyClient 連接 WebSocket


最近在看webSocket netty socket服務
剛起步 在使用websocket時 思考 如果是 使用其他socketclient連接 非web端 是否能接收到socket的數據 經過搜索 找到了一個大佬的博客 (如果不允許請聯系我) 拿來借鑒運行下,保存到自己的博客 方便以后的查看

websocket clien 代碼
MockClientHandler
package nettyclientwebsocket;

  import io.netty.channel.Channel;
  import io.netty.channel.ChannelHandlerContext;
  import io.netty.channel.SimpleChannelInboundHandler;
  import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
  import lombok.extern.slf4j.Slf4j;

  @Slf4j
  public class MockClientHandler extends SimpleChannelInboundHandler<String> {

 
       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();
      }

  }

  
  import io.netty.channel.ChannelInitializer;
  import io.netty.channel.ChannelPipeline;
  import io.netty.channel.socket.SocketChannel;
  import io.netty.handler.codec.http.HttpClientCodec;
  import io.netty.handler.codec.string.StringDecoder;
  import io.netty.handler.codec.string.StringEncoder;
  import io.netty.handler.logging.LogLevel;
  import io.netty.handler.logging.LoggingHandler;

  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);
      }
  }




import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @description:
 * @author: jcZhang
 * @date: 2020-05-20 16:19
 */
@Slf4j
public class TestNettyClientWebSocket {

    public static void main(String[] args) {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            URI uri = new URI("ws://*:*/*?*=*");
            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();
        }
    }
}

  以上的代碼跑過之后發現 與普通的socketclient代碼 有很大的不同 websocket 多了一個握手服務  ,以上搜索就這些了。繼續 下一步


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM