1. public class ClientMsgPackEcho {
    2. private final String host;
    3. public ClientMsgPackEcho(String host) {
    4. this.host = host;
    5. }
    6. public void start() throws InterruptedException {
    7. EventLoopGroup group = new NioEventLoopGroup();/*线程组*/
    8. try {
    9. final Bootstrap b = new Bootstrap();;/*客户端启动必须*/
    10. b.group(group)/*将线程组传入*/
    11. .channel(NioSocketChannel.class)/*指定使用NIO进行网络传输*/
    12. /*配置要连接服务器的ip地址和端口*/
    13. .remoteAddress(
    14. new InetSocketAddress(host, ServerMsgPackEcho.PORT))
    15. .handler(new ChannelInitializerImp());
    16. ChannelFuture f = b.connect().sync();
    17. System.out.println("已连接到服务器.....");
    18. f.channel().closeFuture().sync();
    19. } finally {
    20. group.shutdownGracefully().sync();
    21. }
    22. }
    23. private static class ChannelInitializerImp extends ChannelInitializer<Channel> {
    24. @Override
    25. protected void initChannel(Channel ch) throws Exception {
    26. /*告诉netty,计算一下报文的长度,然后作为报文头加在前面*/
    27. ch.pipeline().addLast(new LengthFieldPrepender(2));
    28. /*对服务器的应答也要解码,解决粘包半包*/
    29. ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
    30. /*对我们要发送的数据做编码-序列化*/
    31. ch.pipeline().addLast(new MsgPackEncode());
    32. ch.pipeline().addLast(new MsgPackClientHandler(5));
    33. }
    34. }
    35. public static void main(String[] args) throws InterruptedException {
    36. new ClientMsgPackEcho("127.0.0.1").start();
    37. }
    38. }