Netty study notes

3 Netty lessons fast and efficient event-driven framework, scalability, and high performance
 4 first wrote helloworld but not discard service is not appropriate. 

The method was originally read client 
two read methods and exception handlers 
 receive data, muting processing msg.release (); 
 abnormal closure line direct link 
Package io.netty.example.discard; 

Import io.netty.buffer.ByteBuf; 

io.netty.channel.ChannelHandlerContext Import; 
Import io.netty.channel.ChannelInboundHandlerAdapter; 

/ * * 
 . * the Handles Server-Side Channel A 
 * / 
public  class the DiscardServerHandler the extends ChannelInboundHandlerAdapter { // (. 1) 

    @Override 
    public  void channelRead (CTX ChannelHandlerContext , Object MSG) { //(2)
         // Discard The Received Data silently. 
        ((ByteBuf) MSG) .release (); // (. 3) 
    } 

    @Override 
    public  void exceptionCaught (CTX ChannelHandlerContext, the cause is the Throwable) { // (. 4)
         // the Close The when iS AN Exception raised Connection. 
        cause.printStackTrace (); 
        ctx.close (); 
    } 
} 

in fact, in both the normal processing is an operation oh 
when reading the message 
@Override 
public  void channelRead (ChannelHandlerContext CTX, Object MSG) { 
    ByteBuf in = (ByteBuf) MSG;
     the try{
         The while ( in .isReadable ()) { // (. 1) 
            the System. OUT .print (( char ) in .readByte ()); 
            the System. OUT .flush (); 
        } 
    } the finally { 
        ReferenceCountUtil.release (MSG); @ (2) 
    } 
} 
( 2 ) is substantially equivalent to that in .release () 
( . 1 ) low cycle efficiency, can be changed, do not understand why, nothing different 
is:. the System OUT .println ( in .toString (io.netty.util.CharsetUtil.US_ASCII))


其实 最主要的main方法调用
package io.netty.example.discard;
    
import io.netty.bootstrap.ServerBootstrap;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
    
/**
 * Discards any incoming data.
 */
public class DiscardServer {
    
    private int port;
    
    public DiscardServer(int port) {
        this.port = port;
    }
    
    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap(); // (2)
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class) // (3)  制定了nioserver
             .childHandler(new ChannelInitializer<SocketChannel>() { // (4) 指定了初始化类
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(new DiscardServerHandler());
                 }
             })
             .option(ChannelOption.SO_BACKLOG, 128)          // (5)
             .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
    
            // Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(port).sync(); // (7)
    
            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
    
    public static void main(String[] args) throws Exception {
        int port = 8080;
        if (args.length > 0) {
            port = Integer.parseInt(args[0 ]); 
        } 

        new new DiscardServer (Port) .run (); 
    } 
} 

wherein NioEventLoopGroup concept multi-threading, and the worker has a boss 
ServerBootstrap a helper class channel can be used to replace, do not move to 
a setting server class 
5 mark represents a pipeline parameter, you can view other parameters ChannelOption. Compiler to improve the 

writing in the actual handler above above 


5 above, there is no reply, the reply had to write a server, after receiving written back? ? 
@Override 
    public  void channelRead (ChannelHandlerContext CTX, Object MSG) { 
        ctx.write (MSG); // (. 1) 
        ctx.flush (); // (2) 
    } 

. 6 write time server, time and the like is a protocol 

9 by default ByteBuf, you can be replaced by pojo 
decoder modified 
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    if (in.readableBytes() < 4) {
        return;
    }

    out.add(new UnixTime(in.readUnsignedInt()));
}
timeclienthandler也修改类型
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    UnixTime m = (UnixTime) msg;
    System.out.println(m);
    ctx.close();
}

Can also modify the server TimeServerHandler 
@Override 
public  void channelActive (ChannelHandlerContext CTX) { 
    ChannelFuture F = ctx.writeAndFlush ( new new UnixTime ()); 
    f.addListener (ChannelFutureListener.CLOSE); 
} 
do not have the processing is encoder section modified to 
package io.netty.example.time; 

public  class TimeEncoder the extends ChannelOutboundHandlerAdapter { 
    @Override 
    public  void Write (ChannelHandlerContext CTX, Object MSG, ChannelPromise Promise) { 
        UnixTime m = (UnixTime) MSG; 
        ByteBuf encoded . ctx.alloc = () Buffer ( . 4 );
        encoded.writeInt (( int ) m.value ()); 
        ctx.write (encoded, Promise); // (1) 
    } 
} 
After summed up a bunch of principle, modify timeencoder his successors like 
public  class TimeEncoder the extends MessageToByteEncoder <UnixTime> { 
    @Override 
    protected  void encode (ChannelHandlerContext CTX, UnixTime MSG, ByteBuf OUT ) {
         OUT .writeInt (( int ) msg.value ()); 
    } 
} 

10 Netty closing

 

Guess you like

Origin www.cnblogs.com/genestart/p/11355715.html