Nettyフレームワークによるtcp通信の実現

4601 ワード

サービス・エンドの起動
*      NIO   ,                ,                。
*      ServerBootstrap  ,  Netty      ,              。
*                ChannelInitializer,          ,              、             。
*      ,                  。
package com.zc.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {
    private static final int port = 8098;
    public void run() throws Exception{
        //NioEventLoopGroup     IO           
        EventLoopGroup bossGroup  = new NioEventLoopGroup();  //          
        EventLoopGroup workerGroup  = new NioEventLoopGroup();//             
        try{
            ServerBootstrap server =new ServerBootstrap();//     NIO        
            server.group(bossGroup,workerGroup )
                    .channel(NioServerSocketChannel.class)  //     Channel        
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //       
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            server.option(ChannelOption.SO_BACKLOG,128);
            server.childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture f = server.bind(port).sync();//     ,         
            System.out.println("       ...");
            //          
            f.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully(); ////  EventLoopGroup,              
            workerGroup.shutdownGracefully();
        }

        //          


    }
    public static void main(String[] args) throws Exception {
        new NettyServer().run();
    }
}
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;

/**
 * @   :zc
 * @  :2018/9/20 0020
 * @  :
 */
public class SimpleChatServerInitializer extends ChannelInitializer {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        //       
        ch.pipeline().addLast(new NettyServerHandler());
    }
}

上のコードはどうしてこのように書くのか、まずこの問題を考えないで、先にこのように書くことをお勧めします.サーバ側の作成として、私たちが主に気にしているのはポートです.どのフレームワーク、どのモデル、socketの主なものはportで、私たちが書く必要がある唯一のビジネスはNettyServer Handlerです.
package com.zc.module.netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.net.InetAddress;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private Log logger = LogFactory.getLog(NettyServerHandler.class);

    //       
    @Override
    public  void channelRead(ChannelHandlerContext ctx, Object  msg) throws Exception {
        try {
            ByteBuf in = (ByteBuf)msg;
            int readableBytes = in.readableBytes();
            byte[] bytes =new byte[readableBytes];
            in.readBytes(bytes);
            System.out.println(new String(bytes));
            //System.out.print(in.toString(CharsetUtil.UTF_8));

            logger.error("         : " + msg);
        }finally {
            //        
            ReferenceCountUtil.release(msg);
        }
    }
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //           
        cause.printStackTrace();
        ctx.close();
    }
    /*
     *      ,    
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //System.out.println("        :" + ctx.channel().remoteAddress());
        logger.error("        :" + ctx.channel().remoteAddress());
        logger.error("      ID:" + ctx.channel().id());
        ctx.writeAndFlush("client"+ InetAddress.getLocalHost().getHostName() + "success connected! 
"); System.out.println("connection"); //StaticVar.ctxList.add(ctx); //StaticVar.chc = ctx; super.channelActive(ctx); } }