netty4初步使用


文件

D:\jp\netty\NtServer.java

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

public final class NtServer {

    static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));

    public static void main(String[] args) throws Exception {


        // Configure the server.
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             // listen 的 BACK_LOG
             .option(ChannelOption.SO_BACKLOG, 511)
             // 日志级别 
             .handler(new LoggingHandler(LogLevel.INFO))
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ChannelPipeline p = ch.pipeline();
                     //处理方法
                     p.addLast(new NtServerHandler());
                 }
             });

            // Start the server.
            ChannelFuture f = b.bind(PORT).sync();

            // Wait until the server socket is closed.
            f.channel().closeFuture().sync();
        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}




D:\jp\netty\NtServerHandler.java

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import io.netty.util.ReferenceCountUtil;
import io.netty.channel.ChannelFutureListener;

@Sharable
public class NtServerHandler extends ChannelInboundHandlerAdapter {
		
    @Override
		public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
			  //ctx.write(msg);//echo测试这行就够了
			  //将接收到的数据转换为String
        ByteBuf buf = (ByteBuf)msg;
				byte[] in = new byte[buf.readableBytes()];
				buf.readBytes(in);
				String body = new String(in);
				System.out.println(body);
				
				//准备回送的数据
        byte[] out = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ").getBytes();
        ByteBuf responeMessage = ctx.alloc().buffer(out.length);
				responeMessage.writeBytes(out);

        //传输完毕后关闭
        ctx.channel().writeAndFlush(responeMessage).addListener(ChannelFutureListener.CLOSE);
				ReferenceCountUtil.release(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}


D:\jp\netty\start.sh


javac -classpath ".;.\*" NtServerHandler.java && javac -classpath ".;.\*" NtServer.java && java -classpath ".;.\*" NtServer





posted on 2016-05-30 11:19  阮減显  阅读(265)  评论(0编辑  收藏  举报

导航