如何在Netty中打开TCP连接(客户端)? [英] How do I open a TCP connection (client) in Netty?

查看:1615
本文介绍了如何在Netty中打开TCP连接(客户端)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看了Netty javadocs了好几个小时了,但我仍然无法弄清楚.如何打开普通的旧TCP连接,例如到Netty中的IRC服务器?

I've been looking at the Netty javadocs for hours and I still can't figure this out. How do I open a plain old TCP connection, e.g. to an IRC server, in Netty?

推荐答案

您可以在netty的github中找到许多演示

假设您正在使用server中的netty5. 您应该将解码器编码器添加到管道中. 像下面的

Assumeing that you are using the netty5 in server . you should add the decoder and encoder to your pipeline. like below

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


}

然后,您可以正常使用阻塞插座进行连接. 这是我的客户演示.

then you can use the blocking socket to connect it as normal . here is my client demo.

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

然后我发送"hello",它会回答相同的单词.

then i send "hello" and it reply the same word .

这是我的客户净值演示

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


}

这篇关于如何在Netty中打开TCP连接(客户端)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆