java - 如何在 Netty 中打开 TCP 连接(客户端)?

标签 java tcp netty

我已经查看 Netty javadoc 好几个小时了,但我仍然无法理解这一点。如何打开一个普通的旧 TCP 连接,例如到 IRC 服务器,在 Netty 中?

最佳答案

you can find many demo in github of netty

假设您在服务器中使用 netty5。 您应该将解码器编码器 添加到您的管道中。 像下面一样

 socketChannel.pipeline().addLast(new StringEncoder() ,new StringDecoder() ,new LineBasedFrameDecoder(1024));

这是我的服务器演示

String  ip ;
int port  = 9999;

NioEventLoopGroup   workGroup = new NioEventLoopGroup(8);
NioEventLoopGroup  bossGroup = new NioEventLoopGroup();
try {
    bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workGroup);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.option(ChannelOption.SO_BACKLOG, 100);
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            socketChannel.pipeline().addLast(new StringEncoder() ,new StringDecoder() ,new LineBasedFrameDecoder(1024));
            socketChannel.pipeline().addLast(new ChannelHandlerAdapter() {
                @Override
                public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
                    System.out.println("the num" +num.getAndIncrement());
                }

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    System.out.println("what i say is :" + msg.toString());
                    ctx.channel().writeAndFlush("from server " + "reply message is " +msg.toString()+"\n");

                }
            });
        }
    });
   ChannelFuture future =  bootstrap.bind(port).sync();
    System.out.println("Server start at port : " + port);
    future.channel().closeFuture().sync();
}catch (Exception e){
    System.out.println("error");
}finally {
    bossGroup.shutdownGracefully();
    workGroup.shutdownGracefully();
}


}

然后你就可以正常使用阻塞套接字来连接它了。 这是我的客户端演示。

Socket socket = new Socket();
    try {
        socket.connect(new InetSocketAddress("localhost" , 9999));
        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream  = socket.getOutputStream();
        outputStream.write("hello".getBytes());
        outputStream.flush();
        InputStreamReader reader = new InputStreamReader(inputStream) ;
        char [] temChar  = new char[40];
        StringBuffer buffer = new StringBuffer( );

        while (reader.read(temChar) != -1){
            buffer.append(temChar);
            System.out.println(buffer.toString() +"\n");
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

然后我发送“你好”,它回复同一个词。

enter image description here

这是我的客户端netty演示

int port  = 9999;
Bootstrap bootstrap ;
NioEventLoopGroup workGroup = new NioEventLoopGroup(8);



    try {
        bootstrap = new Bootstrap();
        bootstrap.group(workGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast( new StringDecoder() ,new StringEncoder( )  , new LineBasedFrameDecoder(1024), new ChannelHandlerAdapter(){
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        System.out.println("recieve method of client : " +msg.toString());
                    }
                });
            }
        });


       NioSocketChannel nioSocketChannel ;

        ChannelFuture future = bootstrap.connect("localhost" , 9999).sync();

        //you can also invoke writeAndFlush() in other thread with channel ,
        //  it is the same as  server   
        System.out.println("try to write hello");
        Channel  channel = future.channel();
        channel.writeAndFlush("hello\n\r");


        future.channel().closeFuture().sync();   //it will block until 
                                                  //   you invoke 
                                                   //   channel.close(); 




        System.out.println("finish: " + port);

    }catch (Exception e){
        e.printStackTrace();
        System.out.println("error");
    }finally {

        workGroup.shutdownGracefully();
    }


}

关于java - 如何在 Netty 中打开 TCP 连接(客户端)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43476643/

相关文章:

winapi - 具有重叠 I/O 的 TCP 连接

java - 如何在Netty中设置请求和响应之间的任意延迟?

java - 使用 Netty 访问 MySql 数据库

java - Selenium Web 驱动程序 - 如何处理 href 链接中的动态

java - ThreadPoolExecutor 和队列

c# - 通过 TCP 接收数据 : MemoryStream contains more data than expected

java - 使用java编程的modbus协议(protocol)问题

java - Netty 中多种数据包类型的解码和编码

java - 在哪里可以下载 JetBrains JDK?

java - 如何使用java查找并列出selenium中ul li标签下的元素和ul li位于div下的元素?