基于Netty最简单的WebSocket通讯_binarywebsocketframe-程序员宅基地

技术标签: Netty  消息协议  Http  WebSocket  

基于Netty最简单的WebSocket通讯

总览

  1. 总共是五个文件:
    • client
      • EasyWsClient 客户端
      • EasyWsClientHandler 客户端消息处理类
    • server
      • EasyWsServer 服务端
      • EasyWsServerHandler 服务端消息处理类
    • EasyWsTest 测试类

  2. EasyWsServer启动时需要声明一个ServerBootstrap,ServerBootstrap里面初始化需要添加一个handler。

  3. WebSocket通讯和普通的tcp通讯不同的是,他有2个格式的消息需要处理
    • 流程:
      • http请求握手
      • 握手完成后的长连接通讯
    • 消息
      • http消息,如:FullHttpRequest、FullHttpResponse等
      • websocket消息,如TextWebSocketFrame(文本类消息),BinaryWebSocketFrame(字节类数据)等

  4. 客户端第一次发送http握手请求的时候,需要使用WebSocketClientHandshaker
  5. 里面处理了文本消息,二进制字节消息。

服务端

EasyWsServer

/*
 * Copyright (C), 2015-2018
 * FileName: EasyWsServer
 * Author:   zhao
 * Date:     2018/8/14 10:43
 * Description: 简单的WebScoket服务器
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.lizhaoblog.demopro.websocket.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * 〈一句话功能简述〉<br>
 * 〈简单的WebScoket服务器〉
 *
 * @author zhao
 * @date 2018/8/14 10:43
 * @since 1.0.1
 */
public class EasyWsServer {
    
  private int port;

  public EasyWsServer(int port) {
    this.port = port;
  }

  public void start() throws InterruptedException {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    serverBootstrap.group(bossGroup, workerGroup);
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.childHandler(new ChannelInitializer() {
      @Override
      protected void initChannel(Channel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();
        pipeline.addLast("http-codec", new HttpServerCodec()); // Http消息编码解码
        pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); // Http消息组装
        pipeline.addLast("http-chunked", new ChunkedWriteHandler()); // WebSocket通信支持
        pipeline.addLast(new EasyWsServerHandler());
      }
    });

    // 监听端口
    ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
    channelFuture.awaitUninterruptibly();
    // 堵塞线程,保持长连接
    channelFuture.channel().closeFuture().sync();
  }

}

EasyWsServerHandler

/*
 * Copyright (C), 2015-2018
 * FileName: EasyWsServerHandler
 * Author:   zhao
 * Date:     2018/8/14 10:44
 * Description: 简单的WebSocket服务器
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.lizhaoblog.demopro.websocket.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.CharsetUtil;

/**
 * 〈一句话功能简述〉<br>
 * 〈简单的WebSocket服务器〉
 *
 * @author zhao
 * @date 2018/8/14 10:44
 * @since 1.0.1
 */
public class EasyWsServerHandler extends SimpleChannelInboundHandler<Object> {
  @Override
  protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
      // 传统的HTTP接入
      handleHttpMessage(channelHandlerContext, msg);
    } else if (msg instanceof WebSocketFrame) {
      // WebSocket接入
      handleWebSocketMessage(channelHandlerContext, msg);
    }

  }

  /**
   * 处理WebSocket中的Http消息
   *
   * @param ctx 上下文
   * @param msg 消息
   */
  private void handleHttpMessage(ChannelHandlerContext ctx, Object msg) {
    // 传统的HTTP接入
    FullHttpRequest request = (FullHttpRequest) msg;

    // 如果HTTP解码失败,返回HHTP异常
    if (!request.decoderResult().isSuccess() || (!"websocket".equals(request.headers().get("Upgrade")))) {
      sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
      return;
    }

    // 正常WebSocket的Http连接请求,构造握手响应返回
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
            "ws://" + request.headers().get(HttpHeaderNames.HOST), null, false);
    WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(request);
    if (handshaker == null) { // 无法处理的websocket版本
      WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else { // 向客户端发送websocket握手,完成握手
      handshaker.handshake(ctx.channel(), request);
    }
  }

  /**
   * Http返回
   *
   * @param ctx
   * @param request
   * @param response
   */
  public static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest request, FullHttpResponse response) {
    // 返回应答给客户端
    if (response.status().code() != 200) {
      ByteBuf buf = Unpooled.copiedBuffer(response.status().toString(), CharsetUtil.UTF_8);
      response.content().writeBytes(buf);
      buf.release();
      HttpUtil.setContentLength(response, response.content().readableBytes());
    }

    // 如果是非Keep-Alive,关闭连接
    ChannelFuture f = ctx.channel().writeAndFlush(response);
    if (!HttpUtil.isKeepAlive(request) || response.status().code() != 200) {
      f.addListener(ChannelFutureListener.CLOSE);
    }
  }

  /**
   * 处理WebSocket中的WebSocket消息
   *
   * @param ctx 上下文
   * @param msg 消息
   */
  private void handleWebSocketMessage(ChannelHandlerContext ctx, Object msg) {
    //    ByteBuf content = ((WebSocketFrame) msg).content();
    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
      TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
      System.out.println("服务器:接收到你的TextWebSocketFrame消息,内容是 " + textFrame.text());

      // 返回消息给客户端
      ctx.writeAndFlush(new TextWebSocketFrame("我是服务器,我是服务器"));

    } else if (frame instanceof BinaryWebSocketFrame) {
      System.out.println("服务器:接收到你的BinaryWebSocketFrame消息,内容是 ");
      ByteBuf content = frame.content();
      byte[] result = new byte[content.readableBytes()];
      content.readBytes(result);
      for (byte b : result) {
        System.out.print(b);
        System.out.print(",");
      }
      System.out.println();
      ctx.writeAndFlush(new BinaryWebSocketFrame(Unpooled.copiedBuffer(result)));
    }

  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) {
    System.out.println("服务器:连接建立");
  }

  @Override
  public void channelInactive(ChannelHandlerContext ctx) {
    System.out.println("服务器:断开连接");
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
    System.out.println("服务器:异常发送");
    throwable.printStackTrace();
  }

}

客户端

EasyWsClient

/*
 * Copyright (C), 2015-2018
 * FileName: EasyWsClient
 * Author:   zhao
 * Date:     2018/8/14 10:23
 * Description: 最简单的websocket客户端
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.lizhaoblog.demopro.websocket.client;

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

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
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.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;

/**
 * 〈一句话功能简述〉<br>
 * 〈最简单的websocket客户端〉
 *
 * @author zhao
 * @date 2018/8/14 10:23
 * @since 1.0.1
 */
public class EasyWsClient {
  private static EventLoopGroup group = new NioEventLoopGroup();
  //  private static final String ip = "127.0.0.1";
  //  private static final int port = 8088;

  private String ip;
  private int port;
  private String uriStr;
  private static EasyWsClientHandler handler;

  public EasyWsClient(String ip, int port) {
    this.ip = ip;
    this.port = port;
    uriStr = "ws//" + ip + ":" + port;
  }

  public void run() throws InterruptedException, URISyntaxException {
    // 主要是为handler(自己写的类)服务,用于初始化EasyWsHandle
    URI wsUri = new URI(uriStr);
    WebSocketClientHandshaker webSocketClientHandshaker = WebSocketClientHandshakerFactory
            .newHandshaker(wsUri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders(), 100 * 1024 * 1024);
    handler = new EasyWsClientHandler(webSocketClientHandshaker);

    // 设置Bootstrap
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group);
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.handler(new ChannelInitializer() {
      @Override
      protected void initChannel(Channel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new HttpClientCodec());
        pipeline.addLast(new HttpObjectAggregator(65536));
        pipeline.addLast(handler);
      }
    });

    // 连接服务端
    ChannelFuture channelFuture = bootstrap.connect(ip, port).sync();
    handler.handshakeFuture().sync();

    // 传输文本
    TextWebSocketFrame frame = new TextWebSocketFrame("hello");
    channelFuture.channel().writeAndFlush(frame);
    // 传输二进制字节数据
    byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    BinaryWebSocketFrame byteFrame = new BinaryWebSocketFrame(Unpooled.copiedBuffer(bytes));
    channelFuture.channel().writeAndFlush(byteFrame);

    // 堵塞线程,保持长连接
    channelFuture.channel().closeFuture().sync();
  }

}

EasyWsClientHandler

/*
 * Copyright (C), 2015-2018
 * FileName: EasyWsClientHandler
 * Author:   zhao
 * Date:     2018/8/14 10:23
 * Description: 最简单的WebSocket的handle
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.lizhaoblog.demopro.websocket.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.CharsetUtil;

/**
 * 〈一句话功能简述〉<br>
 * 〈最简单的WebSocket的handle〉
 *
 * @author zhao
 * @date 2018/8/14 10:23
 * @since 1.0.1
 */
public class EasyWsClientHandler extends SimpleChannelInboundHandler<Object> {
  private final WebSocketClientHandshaker handshaker;
  private ChannelPromise handshakeFuture;

  public EasyWsClientHandler(WebSocketClientHandshaker handshaker) {
    this.handshaker = handshaker;
  }

  public ChannelFuture handshakeFuture() {
    return handshakeFuture;
  }

  @Override
  public void handlerAdded(ChannelHandlerContext ctx) {
    handshakeFuture = ctx.newPromise();
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("客户端连接建立");
    // 在通道连接成功后发送握手连接
    handshaker.handshake(ctx.channel());
    super.channelActive(ctx);
  }

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();

    // 这里是第一次使用http连接成功的时候
    if (!handshaker.isHandshakeComplete()) {
      handshaker.finishHandshake(ch, (FullHttpResponse) msg);
      System.out.println("WebSocket Client connected!");
      handshakeFuture.setSuccess();
      return;
    }

    // 这里是第一次使用http连接失败的时候
    if (msg instanceof FullHttpResponse) {
      FullHttpResponse response = (FullHttpResponse) msg;
      throw new IllegalStateException(
              "Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content()
                      .toString(CharsetUtil.UTF_8) + ')');
    }

    // 这里是服务器与客户端进行通讯的
    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
      TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
      System.out.println("客户端:接收到TextWebSocketFrame消息,消息内容是-- " + textFrame.text());
    } else if (frame instanceof BinaryWebSocketFrame) {
      System.out.println("客户端:接收到BinaryWebSocketFrame消息,消息内容是-- ");
      ByteBuf content = frame.content();
      byte[] result = new byte[content.readableBytes()];
      content.readBytes(result);
      for (byte b : result) {
        System.out.print(b);
        System.out.print(",");
      }
      System.out.println();
    } else if (frame instanceof PongWebSocketFrame) {
      System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
      System.out.println("WebSocket Client received closing");
      ch.close();
    }

  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable arg1) {
    System.out.println("异常发生");
    arg1.printStackTrace();
  }

  @Override
  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("客户端连接断开");
    super.channelInactive(ctx);
  }
}

测试类

EasyWsTest

/*
 * Copyright (C), 2015-2018
 * FileName: EasyWsTest
 * Author:   zhao
 * Date:     2018/8/14 11:08
 * Description: EasyWs的测试类
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.lizhaoblog.demopro.websocket;

import com.lizhaoblog.demopro.websocket.client.EasyWsClient;
import com.lizhaoblog.demopro.websocket.server.EasyWsServer;

import org.junit.Test;

/**
 * 〈一句话功能简述〉<br>
 * 〈EasyWs的测试类〉
 *
 * @author zhao
 * @date 2018/8/14 11:08
 * @since 1.0.1
 */
public class EasyWsTest {
    

  private static final String IP = "127.0.0.1";
  private static final int PORT = 8088;

  @Test
  public void startServer() throws Exception {
    EasyWsServer easyWsServer = new EasyWsServer(PORT);
    easyWsServer.start();
  }

  @Test
  public void startClient() throws Exception {
    EasyWsClient easyWsClient = new EasyWsClient(IP, PORT);
    easyWsClient.run();
  }
}

测试

  1. 打开EasyWsTest,运行startServer
  2. 打开EasyWsTest,运行startClient
  3. 查看结果
    • 服务端:连接建立–服务器收到http握手消息–服务器收到消息(文本)–服务器收到字节消息
    • 服务端
Connected to the target VM, address: '127.0.0.1:3215', transport: 'socket'
2018-08-14 11:55:39.087 DEBUG io.netty.util.internal.logging.InternalLoggerFactory - Using SLF4J as the default logging framework
2018-08-14 11:55:39.099 DEBUG io.netty.channel.MultithreadEventLoopGroup - -Dio.netty.eventLoopThreads: 16
2018-08-14 11:55:39.122 DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Buffer.address: available
2018-08-14 11:55:39.123 DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.theUnsafe: available
2018-08-14 11:55:39.123 DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.copyMemory: available
2018-08-14 11:55:39.124 DEBUG io.netty.util.internal.PlatformDependent0 - direct buffer constructor: available
2018-08-14 11:55:39.125 DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Bits.unaligned: available, true
2018-08-14 11:55:39.125 DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.DirectByteBuffer.<init>(long, int): available
2018-08-14 11:55:39.126 DEBUG io.netty.util.internal.Cleaner0 - java.nio.ByteBuffer.cleaner(): available
2018-08-14 11:55:39.126 DEBUG io.netty.util.internal.PlatformDependent - Platform: Windows
2018-08-14 11:55:39.127 DEBUG io.netty.util.internal.PlatformDependent - Java version: 8
2018-08-14 11:55:39.127 DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.noUnsafe: false
2018-08-14 11:55:39.127 DEBUG io.netty.util.internal.PlatformDependent - sun.misc.Unsafe: available
2018-08-14 11:55:39.127 DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.noJavassist: false
2018-08-14 11:55:39.128 DEBUG io.netty.util.internal.PlatformDependent - Javassist: unavailable
2018-08-14 11:55:39.128 DEBUG io.netty.util.internal.PlatformDependent - You don't have Javassist in your class path or you don't have enough permission to load dynamically generated classes.  Please check the configuration for better performance.
2018-08-14 11:55:39.129 DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.tmpdir: C:\Users\ADMINI~1\AppData\Local\Temp (java.io.tmpdir)
2018-08-14 11:55:39.129 DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.bitMode: 64 (sun.arch.data.model)
2018-08-14 11:55:39.129 DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.noPreferDirect: false
2018-08-14 11:55:39.129 DEBUG io.netty.util.internal.PlatformDependent - io.netty.maxDirectMemory: 3806855168 bytes
2018-08-14 11:55:39.183 DEBUG io.netty.channel.nio.NioEventLoop - -Dio.netty.noKeySetOptimization: false
2018-08-14 11:55:39.184 DEBUG io.netty.channel.nio.NioEventLoop - -Dio.netty.selectorAutoRebuildThreshold: 512
2018-08-14 11:55:39.186 DEBUG io.netty.util.internal.PlatformDependent - org.jctools-core.MpscChunkedArrayQueue: available
2018-08-14 11:55:39.380 DEBUG io.netty.channel.DefaultChannelId - -Dio.netty.processId: 6492 (auto-detected)
2018-08-14 11:55:39.382 DEBUG io.netty.util.NetUtil - -Djava.net.preferIPv4Stack: false
2018-08-14 11:55:39.383 DEBUG io.netty.util.NetUtil - -Djava.net.preferIPv6Addresses: false
2018-08-14 11:55:39.411 DEBUG io.netty.util.NetUtil - Loopback interface: lo (Software Loopback Interface 1, 127.0.0.1)
2018-08-14 11:55:39.412 DEBUG io.netty.util.NetUtil - \proc\sys\net\core\somaxconn: 200 (non-existent)
2018-08-14 11:55:39.444 DEBUG io.netty.channel.DefaultChannelId - -Dio.netty.machineId: 94:de:80:ff:fe:78:f9:54 (auto-detected)
2018-08-14 11:55:39.447 DEBUG io.netty.util.internal.ThreadLocalRandom - -Dio.netty.initialSeedUniquifier: 0x912cf1a5dfc99b85
2018-08-14 11:55:39.466 DEBUG io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.level: simple
2018-08-14 11:55:39.467 DEBUG io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.maxRecords: 4
2018-08-14 11:55:39.497 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.numHeapArenas: 16
2018-08-14 11:55:39.497 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.numDirectArenas: 16
2018-08-14 11:55:39.498 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.pageSize: 8192
2018-08-14 11:55:39.498 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.maxOrder: 11
2018-08-14 11:55:39.498 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.chunkSize: 16777216
2018-08-14 11:55:39.498 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.tinyCacheSize: 512
2018-08-14 11:55:39.498 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.smallCacheSize: 256
2018-08-14 11:55:39.498 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.normalCacheSize: 64
2018-08-14 11:55:39.498 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.maxCachedBufferCapacity: 32768
2018-08-14 11:55:39.498 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.cacheTrimInterval: 8192
2018-08-14 11:55:39.512 DEBUG io.netty.buffer.ByteBufUtil - -Dio.netty.allocator.type: pooled
2018-08-14 11:55:39.513 DEBUG io.netty.buffer.ByteBufUtil - -Dio.netty.threadLocalDirectBufferSize: 65536
2018-08-14 11:55:39.513 DEBUG io.netty.buffer.ByteBufUtil - -Dio.netty.maxThreadLocalCharBufferSize: 16384
2018-08-14 11:55:42.719 DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.bytebuf.checkAccessible: true
2018-08-14 11:55:42.724 DEBUG io.netty.util.ResourceLeakDetectorFactory - Loaded default ResourceLeakDetector: io.netty.util.ResourceLeakDetector@42e2b085
服务器:连接建立
2018-08-14 11:55:42.788 DEBUG io.netty.util.Recycler - -Dio.netty.recycler.maxCapacityPerThread: 32768
2018-08-14 11:55:42.788 DEBUG io.netty.util.Recycler - -Dio.netty.recycler.maxSharedCapacityFactor: 2
2018-08-14 11:55:42.788 DEBUG io.netty.util.Recycler - -Dio.netty.recycler.linkCapacity: 16
2018-08-14 11:55:42.788 DEBUG io.netty.util.Recycler - -Dio.netty.recycler.ratio: 8
2018-08-14 11:55:42.836 DEBUG io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker - [id: 0x08778b2d, L:/127.0.0.1:8088 - R:/127.0.0.1:3327] WebSocket version V13 server handshake
2018-08-14 11:55:42.842 DEBUG io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker - WebSocket version 13 server handshake key: YR/wvrnrJz9kEkn6LSuFug==, response: 6XulC19MJ2P54cdvYMhyy/OHqNU=
2018-08-14 11:55:42.871 DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder - Decoding WebSocket Frame opCode=1
2018-08-14 11:55:42.871 DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder - Decoding WebSocket Frame length=5
服务器:接收到你的TextWebSocketFrame消息,内容是 hello
2018-08-14 11:55:42.873 DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder - Encoding WebSocket Frame opCode=1 length=33
2018-08-14 11:55:42.874 DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder - Decoding WebSocket Frame opCode=2
2018-08-14 11:55:42.874 DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder - Decoding WebSocket Frame length=9
服务器:接收到你的BinaryWebSocketFrame消息,内容是 
1,2,3,4,5,6,7,8,9,
2018-08-14 11:55:42.879 DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder - Encoding WebSocket Frame opCode=2 length=9
Disconnected from the target VM, address: '127.0.0.1:3215', transport: 'socket'

Process finished with exit code -1
- 客户端
2018-08-14 11:55:42.240 DEBUG io.netty.util.internal.logging.InternalLoggerFactory - Using SLF4J as the default logging framework
2018-08-14 11:55:42.246 DEBUG io.netty.channel.MultithreadEventLoopGroup - -Dio.netty.eventLoopThreads: 16
2018-08-14 11:55:42.271 DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Buffer.address: available
2018-08-14 11:55:42.272 DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.theUnsafe: available
2018-08-14 11:55:42.272 DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.copyMemory: available
2018-08-14 11:55:42.273 DEBUG io.netty.util.internal.PlatformDependent0 - direct buffer constructor: available
2018-08-14 11:55:42.274 DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Bits.unaligned: available, true
2018-08-14 11:55:42.274 DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.DirectByteBuffer.<init>(long, int): available
2018-08-14 11:55:42.275 DEBUG io.netty.util.internal.Cleaner0 - java.nio.ByteBuffer.cleaner(): available
2018-08-14 11:55:42.276 DEBUG io.netty.util.internal.PlatformDependent - Platform: Windows
2018-08-14 11:55:42.277 DEBUG io.netty.util.internal.PlatformDependent - Java version: 8
2018-08-14 11:55:42.277 DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.noUnsafe: false
2018-08-14 11:55:42.277 DEBUG io.netty.util.internal.PlatformDependent - sun.misc.Unsafe: available
2018-08-14 11:55:42.277 DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.noJavassist: false
2018-08-14 11:55:42.278 DEBUG io.netty.util.internal.PlatformDependent - Javassist: unavailable
2018-08-14 11:55:42.279 DEBUG io.netty.util.internal.PlatformDependent - You don't have Javassist in your class path or you don't have enough permission to load dynamically generated classes.  Please check the configuration for better performance.
2018-08-14 11:55:42.279 DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.tmpdir: C:\Users\ADMINI~1\AppData\Local\Temp (java.io.tmpdir)
2018-08-14 11:55:42.279 DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.bitMode: 64 (sun.arch.data.model)
2018-08-14 11:55:42.282 DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.noPreferDirect: false
2018-08-14 11:55:42.282 DEBUG io.netty.util.internal.PlatformDependent - io.netty.maxDirectMemory: 3806855168 bytes
2018-08-14 11:55:42.301 DEBUG io.netty.channel.nio.NioEventLoop - -Dio.netty.noKeySetOptimization: false
2018-08-14 11:55:42.301 DEBUG io.netty.channel.nio.NioEventLoop - -Dio.netty.selectorAutoRebuildThreshold: 512
2018-08-14 11:55:42.303 DEBUG io.netty.util.internal.PlatformDependent - org.jctools-core.MpscChunkedArrayQueue: available
2018-08-14 11:55:42.488 DEBUG io.netty.channel.DefaultChannelId - -Dio.netty.processId: 18412 (auto-detected)
2018-08-14 11:55:42.490 DEBUG io.netty.util.NetUtil - -Djava.net.preferIPv4Stack: false
2018-08-14 11:55:42.491 DEBUG io.netty.util.NetUtil - -Djava.net.preferIPv6Addresses: false
2018-08-14 11:55:42.516 DEBUG io.netty.util.NetUtil - Loopback interface: lo (Software Loopback Interface 1, 127.0.0.1)
2018-08-14 11:55:42.518 DEBUG io.netty.util.NetUtil - \proc\sys\net\core\somaxconn: 200 (non-existent)
2018-08-14 11:55:42.545 DEBUG io.netty.channel.DefaultChannelId - -Dio.netty.machineId: 94:de:80:ff:fe:78:f9:54 (auto-detected)
2018-08-14 11:55:42.546 DEBUG io.netty.util.internal.ThreadLocalRandom - -Dio.netty.initialSeedUniquifier: 0x30542ca8d536a1bd
2018-08-14 11:55:42.561 DEBUG io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.level: simple
2018-08-14 11:55:42.561 DEBUG io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.maxRecords: 4
2018-08-14 11:55:42.590 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.numHeapArenas: 16
2018-08-14 11:55:42.591 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.numDirectArenas: 16
2018-08-14 11:55:42.591 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.pageSize: 8192
2018-08-14 11:55:42.591 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.maxOrder: 11
2018-08-14 11:55:42.591 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.chunkSize: 16777216
2018-08-14 11:55:42.591 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.tinyCacheSize: 512
2018-08-14 11:55:42.591 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.smallCacheSize: 256
2018-08-14 11:55:42.592 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.normalCacheSize: 64
2018-08-14 11:55:42.592 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.maxCachedBufferCapacity: 32768
2018-08-14 11:55:42.592 DEBUG io.netty.buffer.PooledByteBufAllocator - -Dio.netty.allocator.cacheTrimInterval: 8192
2018-08-14 11:55:42.606 DEBUG io.netty.buffer.ByteBufUtil - -Dio.netty.allocator.type: pooled
2018-08-14 11:55:42.606 DEBUG io.netty.buffer.ByteBufUtil - -Dio.netty.threadLocalDirectBufferSize: 65536
2018-08-14 11:55:42.606 DEBUG io.netty.buffer.ByteBufUtil - -Dio.netty.maxThreadLocalCharBufferSize: 16384
2018-08-14 11:55:42.645 DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.bytebuf.checkAccessible: true
2018-08-14 11:55:42.648 DEBUG io.netty.util.ResourceLeakDetectorFactory - Loaded default ResourceLeakDetector: io.netty.util.ResourceLeakDetector@3724974
客户端连接建立
2018-08-14 11:55:42.681 DEBUG io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker13 - WebSocket version 13 client handshake key: YR/wvrnrJz9kEkn6LSuFug==, expected response: 6XulC19MJ2P54cdvYMhyy/OHqNU=
2018-08-14 11:55:42.690 DEBUG io.netty.util.Recycler - -Dio.netty.recycler.maxCapacityPerThread: 32768
2018-08-14 11:55:42.690 DEBUG io.netty.util.Recycler - -Dio.netty.recycler.maxSharedCapacityFactor: 2
2018-08-14 11:55:42.690 DEBUG io.netty.util.Recycler - -Dio.netty.recycler.linkCapacity: 16
2018-08-14 11:55:42.690 DEBUG io.netty.util.Recycler - -Dio.netty.recycler.ratio: 8
WebSocket Client connected!
2018-08-14 11:55:42.869 DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder - Encoding WebSocket Frame opCode=1 length=5
2018-08-14 11:55:42.872 DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder - Encoding WebSocket Frame opCode=2 length=9
2018-08-14 11:55:42.875 DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder - Decoding WebSocket Frame opCode=1
2018-08-14 11:55:42.875 DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder - Decoding WebSocket Frame length=33
客户端:接收到TextWebSocketFrame消息,消息内容是-- 我是服务器,我是服务器
2018-08-14 11:55:42.879 DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder - Decoding WebSocket Frame opCode=2
2018-08-14 11:55:42.880 DEBUG io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder - Decoding WebSocket Frame length=9
客户端:接收到BinaryWebSocketFrame消息,消息内容是-- 
1,2,3,4,5,6,7,8,9,

上面的代码在码云上 https://gitee.com/lizhaoandroid/JgServer
的test下的com.lizhaoblog.demopro.websocket包目录下,可以下载查看

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/cmqwan/article/details/81673267

智能推荐

什么是内部类?成员内部类、静态内部类、局部内部类和匿名内部类的区别及作用?_成员内部类和局部内部类的区别-程序员宅基地

文章浏览阅读3.4k次,点赞8次,收藏42次。一、什么是内部类?or 内部类的概念内部类是定义在另一个类中的类;下面类TestB是类TestA的内部类。即内部类对象引用了实例化该内部对象的外围类对象。public class TestA{ class TestB {}}二、 为什么需要内部类?or 内部类有什么作用?1、 内部类方法可以访问该类定义所在的作用域中的数据,包括私有数据。2、内部类可以对同一个包中的其他类隐藏起来。3、 当想要定义一个回调函数且不想编写大量代码时,使用匿名内部类比较便捷。三、 内部类的分类成员内部_成员内部类和局部内部类的区别

分布式系统_分布式系统运维工具-程序员宅基地

文章浏览阅读118次。分布式系统要求拆分分布式思想的实质搭配要求分布式系统要求按照某些特定的规则将项目进行拆分。如果将一个项目的所有模板功能都写到一起,当某个模块出现问题时将直接导致整个服务器出现问题。拆分按照业务拆分为不同的服务器,有效的降低系统架构的耦合性在业务拆分的基础上可按照代码层级进行拆分(view、controller、service、pojo)分布式思想的实质分布式思想的实质是为了系统的..._分布式系统运维工具

用Exce分析l数据极简入门_exce l趋势分析数据量-程序员宅基地

文章浏览阅读174次。1.数据源准备2.数据处理step1:数据表处理应用函数:①VLOOKUP函数; ② CONCATENATE函数终表:step2:数据透视表统计分析(1) 透视表汇总不同渠道用户数, 金额(2)透视表汇总不同日期购买用户数,金额(3)透视表汇总不同用户购买订单数,金额step3:讲第二步结果可视化, 比如, 柱形图(1)不同渠道用户数, 金额(2)不同日期..._exce l趋势分析数据量

宁盾堡垒机双因素认证方案_horizon宁盾双因素配置-程序员宅基地

文章浏览阅读3.3k次。堡垒机可以为企业实现服务器、网络设备、数据库、安全设备等的集中管控和安全可靠运行,帮助IT运维人员提高工作效率。通俗来说,就是用来控制哪些人可以登录哪些资产(事先防范和事中控制),以及录像记录登录资产后做了什么事情(事后溯源)。由于堡垒机内部保存着企业所有的设备资产和权限关系,是企业内部信息安全的重要一环。但目前出现的以下问题产生了很大安全隐患:密码设置过于简单,容易被暴力破解;为方便记忆,设置统一的密码,一旦单点被破,极易引发全面危机。在单一的静态密码验证机制下,登录密码是堡垒机安全的唯一_horizon宁盾双因素配置

谷歌浏览器安装(Win、Linux、离线安装)_chrome linux debian离线安装依赖-程序员宅基地

文章浏览阅读7.7k次,点赞4次,收藏16次。Chrome作为一款挺不错的浏览器,其有着诸多的优良特性,并且支持跨平台。其支持(Windows、Linux、Mac OS X、BSD、Android),在绝大多数情况下,其的安装都很简单,但有时会由于网络原因,无法安装,所以在这里总结下Chrome的安装。Windows下的安装:在线安装:离线安装:Linux下的安装:在线安装:离线安装:..._chrome linux debian离线安装依赖

烤仔TVの尚书房 | 逃离北上广?不如押宝越南“北上广”-程序员宅基地

文章浏览阅读153次。中国发达城市榜单每天都在刷新,但无非是北上广轮流坐庄。北京拥有最顶尖的文化资源,上海是“摩登”的国际化大都市,广州是活力四射的千年商都。GDP和发展潜力是衡量城市的数字指...

随便推点

java spark的使用和配置_使用java调用spark注册进去的程序-程序员宅基地

文章浏览阅读3.3k次。前言spark在java使用比较少,多是scala的用法,我这里介绍一下我在项目中使用的代码配置详细算法的使用请点击我主页列表查看版本jar版本说明spark3.0.1scala2.12这个版本注意和spark版本对应,只是为了引jar包springboot版本2.3.2.RELEASEmaven<!-- spark --> <dependency> <gro_使用java调用spark注册进去的程序

汽车零部件开发工具巨头V公司全套bootloader中UDS协议栈源代码,自己完成底层外设驱动开发后,集成即可使用_uds协议栈 源代码-程序员宅基地

文章浏览阅读4.8k次。汽车零部件开发工具巨头V公司全套bootloader中UDS协议栈源代码,自己完成底层外设驱动开发后,集成即可使用,代码精简高效,大厂出品有量产保证。:139800617636213023darcy169_uds协议栈 源代码

AUTOSAR基础篇之OS(下)_autosar 定义了 5 种多核支持类型-程序员宅基地

文章浏览阅读4.6k次,点赞20次,收藏148次。AUTOSAR基础篇之OS(下)前言首先,请问大家几个小小的问题,你清楚:你知道多核OS在什么场景下使用吗?多核系统OS又是如何协同启动或者关闭的呢?AUTOSAR OS存在哪些功能安全等方面的要求呢?多核OS之间的启动关闭与单核相比又存在哪些异同呢?。。。。。。今天,我们来一起探索并回答这些问题。为了便于大家理解,以下是本文的主题大纲:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JCXrdI0k-1636287756923)(https://gite_autosar 定义了 5 种多核支持类型

VS报错无法打开自己写的头文件_vs2013打不开自己定义的头文件-程序员宅基地

文章浏览阅读2.2k次,点赞6次,收藏14次。原因:自己写的头文件没有被加入到方案的包含目录中去,无法被检索到,也就无法打开。将自己写的头文件都放入header files。然后在VS界面上,右键方案名,点击属性。将自己头文件夹的目录添加进去。_vs2013打不开自己定义的头文件

【Redis】Redis基础命令集详解_redis命令-程序员宅基地

文章浏览阅读3.3w次,点赞80次,收藏342次。此时,可以将系统中所有用户的 Session 数据全部保存到 Redis 中,用户在提交新的请求后,系统先从Redis 中查找相应的Session 数据,如果存在,则再进行相关操作,否则跳转到登录页面。此时,可以将系统中所有用户的 Session 数据全部保存到 Redis 中,用户在提交新的请求后,系统先从Redis 中查找相应的Session 数据,如果存在,则再进行相关操作,否则跳转到登录页面。当数据量很大时,count 的数量的指定可能会不起作用,Redis 会自动调整每次的遍历数目。_redis命令

URP渲染管线简介-程序员宅基地

文章浏览阅读449次,点赞3次,收藏3次。URP的设计目标是在保持高性能的同时,提供更多的渲染功能和自定义选项。与普通项目相比,会多出Presets文件夹,里面包含着一些设置,包括本色,声音,法线,贴图等设置。全局只有主光源和附加光源,主光源只支持平行光,附加光源数量有限制,主光源和附加光源在一次Pass中可以一起着色。URP:全局只有主光源和附加光源,主光源只支持平行光,附加光源数量有限制,一次Pass可以计算多个光源。可编程渲染管线:渲染策略是可以供程序员定制的,可以定制的有:光照计算和光源,深度测试,摄像机光照烘焙,后期处理策略等等。_urp渲染管线

推荐文章

热门文章

相关标签