Netty—TCP服务器

一.概述

Netty一个高性能IO工具包,主要用于开发HTTP服务器,HTTPS服务器,WebSocket服务器,TCP服务器,UDP服务器和在JVM管道。用Netty开发的服务器可单独运行(即:在main()函数里调用),不需要部署在类似tomcat的容器里。Netty使用单线程并发模型,并围绕非阻塞NIO设计,所以性能较高。

二.TCP服务器

public class NerryTcpServer {
	public static void main(String[] args) {
		EventLoopGroup group = new NioEventLoopGroup();
		ServerBootstrap bootstrap = new ServerBootstrap();

		bootstrap.group(group);
		bootstrap.channel(NioServerSocketChannel.class);

		bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			protected void initChannel(SocketChannel socketChannel) throws Exception {
				socketChannel.pipeline().addLast(new NettyServerHandler());
			}
		});

		try {
			ChannelFuture channelFuture = bootstrap.bind(8899).sync();
			channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}
	}
}

class NettyServerHandler extends SimpleChannelInboundHandler<String> {
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		System.out.println("客户端消息:" + msg);
		ctx.channel().writeAndFlush("服务器消息:hello word");
	}

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

二.TCP客户端

public class NettyTcpClient {
	public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer(){
			@Override
			protected void initChannel(Channel channel) throws Exception {
				channel.pipeline().addLast(new NettyClientHandler());
			}        	
        });

        try {
            ChannelFuture channelFuture = bootstrap.connect("localhost", 8899).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }
}

class NettyClientHandler  extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {       
        System.out.println("服务端消息:" + msg);
        ctx.channel().writeAndFlush("客户端消息:hello word");
    }
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐