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





转载于:https://www.cnblogs.com/ruanjianxian/p/6126849.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值