3, netty second example, the use of netty build client and server communication

In the first example, the establishment of a http server, you can use the curl command directly, or direct browser access.

In the second example, a netty build customer terminal sends a request to the analog browser sends the request.

Here to start the server, and then start the client, start the client, in channelActive approach, the initiative to send a message to the server, the server-side channelRead0 method, after receiving news of the client, the client will again return message. ChannelRead0 client process receives the message sent by the client message again, successively reciprocate.

Similarly, in order

 

client

 1 import io.netty.bootstrap.Bootstrap;
 2 import io.netty.channel.ChannelFuture;
 3 import io.netty.channel.EventLoopGroup;
 4 import io.netty.channel.nio.NioEventLoopGroup;
 5 import io.netty.channel.socket.nio.NioServerSocketChannel;
 6 import io.netty.channel.socket.nio.NioSocketChannel;
 7 
 8 public class MyClient {
 9     public static void main(String[] args) throws InterruptedException {
10         //客户端只需要一个
11         EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
12 
13         try{
14 
15             Bootstrap bootstrap = new Bootstrap();
16             bootstrap.group(eventLoopGroup)
17                     .channel(NioSocketChannel.class)
18                     .handler(new MyClientInitlalizer());
19             ChannelFuture channelFuture = bootstrap.connect("localhost", 8899).sync();
20 
21             //channelFuture.channel().writeAndFlush("first msg");//Data transmission, in fact, should be written in the active method handler 
22 is  
23 is              channelFuture.channel () closeFuture () Sync ();..
 24  
25          } the finally {
 26 is              eventLoopGroup.shutdownGracefully ();
 27          }
 28  
29      }
 30 }

 

Initlalizer

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class MyClientInitlalizer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception { 
        the ChannelPipeline the ChannelPipeline = ch.pipeline (); 

        // add handler decoder 
        channelPipeline.addLast ( new new LengthFieldBasedFrameDecoder (Integer.MAX_VALUE, 0,4,0,4 )); 

        channelPipeline.addLast ( new new LengthFieldPrepender (. 4 )) ;
         // decoder string 
        channelPipeline.addLast ( new new StringDecoder (CharsetUtil.UTF_8));
         // encoder string 
        channelPipeline.addLast ( new new StringEncoder (CharsetUtil.UTF_8));
         // custom processor 
        channelPipeline. addLast ( new new MyClientHandler());
    }
}

 

handler

 1 import io.netty.channel.ChannelHandlerContext;
 2 import io.netty.channel.SimpleChannelInboundHandler;
 3 
 4 import java.time.LocalDateTime;
 5 
 6 public class MyClientHandler  extends SimpleChannelInboundHandler<String> {
 7     @Override
 8     protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
 9         System.out.println( ctx.channel().remoteAddress() + "," + msg);
10         System.out.println( "client output:" + msg);
11 
12         ctx.writeAndFlush("from client" + LocalDateTime.now());
13     }
14 
15     @Override
16     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
17         cause.printStackTrace();
18         ctx.close();
19         //super.exceptionCaught(ctx, cause);
20     }
21 
22     @Override
23     public void channelActive(ChannelHandlerContext ctx) throws Exception {
24         . ctx.channel () writeAndFlush ( "greetings from the client!"); // after the channel is connected, the transmission data 
25          Super .channelActive (CTX);
 26 is      }
 27 }

 

sever the handle

server in the server code is similar to the first example, initlializer and client is consistent, not posted code.

public class MyServerHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "," + msg);

        ctx.writeAndFlush("from serevber" + UUID.randomUUID());//消息返回
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
//      super.exceptionCaught(ctx, cause);
    }
}

 

Guess you like

Origin www.cnblogs.com/amibandoufu/p/11442688.html