netty入门demo

来源:互联网 发布:路由器访客网络限制 编辑:程序博客网 时间:2024/05/16 16:59

在公司最近用到netty,所以研究了下,写了个demo。

服务端如下:

package smu.gaoyi.netty;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;/** * Netty服务端 *  * @author gaoyi * */public class Server {private void bind(int port) {EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try {//服务端辅助启动类,用以降低服务端的开发复杂度ServerBootstrap bootstrap = new ServerBootstrap();bootstrap.group(bossGroup, workerGroup)//实例化ServerSocketChannel.channel(NioServerSocketChannel.class)//设置ServerSocketChannel的TCP参数.option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChildChannelHandler());// ChannelFuture:代表异步I/O的结果ChannelFuture f = bootstrap.bind(port).sync();f.channel().closeFuture().sync();} catch (InterruptedException e) {System.out.println("启动netty服务异常");e.printStackTrace();} finally {workerGroup.shutdownGracefully();            bossGroup.shutdownGracefully();}}private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {//handlerch.pipeline().addLast(new ServerHandler());}}public static void main(String[] args) {int port = 8888;new Server().bind(port);}}

服务端的handler:

package smu.gaoyi.netty;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;/** * Handles a server-side channel. * @author yi.gao * */public class ServerHandler extends ChannelInboundHandlerAdapter{@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {ByteBuf buf = (ByteBuf)msg;byte[] bytes = new byte[buf.readableBytes()];buf.readBytes(bytes);String message = new String(bytes, "UTF-8");System.out.println("服务端收到的消息: " + message);//向客户端写数据String response = "hello client";ByteBuf buffer = Unpooled.copiedBuffer(response.getBytes());ctx.write(buffer);//写入缓冲数组}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {System.out.println("channelReadComplete...");ctx.flush();//将缓冲区数据写入SocketChannel}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {System.out.println("exceptionCaught...");}}

客户端:

package smu.gaoyi.netty;import io.netty.bootstrap.Bootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;public class Client {public void connect(String host, int port) throws Exception {EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(new ClientHandler());}});ChannelFuture future = bootstrap.connect(host, port).sync();future.channel().closeFuture().sync();} finally {group.shutdownGracefully();}}public static void main(String[] args) throws Exception {new Client().connect("localhost", 8888);}}

客户端的handler:

package smu.gaoyi.netty;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;public class ClientHandler extends ChannelInboundHandlerAdapter{private final ByteBuf byteBuf;public ClientHandler() {byte[] bytes = "i love you".getBytes();byteBuf = Unpooled.buffer(bytes.length);byteBuf.writeBytes(bytes);//写入buffer }@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {//向服务端发送数据ctx.writeAndFlush(byteBuf);}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//读取服务端发过来的数据ByteBuf buf = (ByteBuf)msg;byte[] bytes = new byte[buf.readableBytes()];buf.readBytes(bytes);String message = new String(bytes, "UTF-8");System.out.println("客户端收到的消息: " + message);}}



0 0