标签:style blog http io os ar java strong sp
既然是入门,那我们就在这里写一个简单的Demo,client发送一个字符串到server端,server端接收字符串后再发送回client。
2.1、配置开发环境
package NettyDemo.echo.server; import io.netty.bootstrap.ServerBootstrap; 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.NioServerSocketChannel; import java.net.InetSocketAddress; import NettyDemo.echo.handler.EchoServerHandler; public class EchoServer { private static final int port = 8080; public void start() throws InterruptedException { ServerBootstrap b = new ServerBootstrap();// 引导辅助程序 EventLoopGroup group = new NioEventLoopGroup();// 通过nio方式来接收连接和处理连接 try { b.group(group); b.channel(NioServerSocketChannel.class);// 设置nio类型的channel b.localAddress(new InetSocketAddress(port));// 设置监听端口 b.childHandler(new ChannelInitializer<SocketChannel>() {//有连接到达时会创建一个channel protected void initChannel(SocketChannel ch) throws Exception { // pipeline管理channel中的Handler,在channel队列中加入一个handler来处理业务 ch.pipeline().addLast("myHandler", new EchoServerHandler()); } }); ChannelFuture f = b.bind().sync();// 配置完毕,開始绑定server,通过调用sync同步方法堵塞直到绑定成功 System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress()); f.channel().closeFuture().sync();// 应用程序会一直等待,直到channel关闭 } catch (Exception e) { e.printStackTrace(); } finally { group.shutdownGracefully().sync();//关闭EventLoopGroup,释放掉全部资源包含创建的线程 } } public static void main(String[] args) { try { new EchoServer().start(); } catch (InterruptedException e) { e.printStackTrace(); } } }
package NettyDemo.echo.handler; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelHandler.Sharable; /** * Sharable表示此对象在channel间共享 * handler类是我们的详细业务类 * */ @Sharable//注解@Sharable能够让它在channels间共享 public class EchoServerHandler extends ChannelInboundHandlerAdapter{ public void channelRead(ChannelHandlerContext ctx, Object msg) { System.out.println("server received data :" + msg); ctx.write(msg);//写回数据, } public void channelReadComplete(ChannelHandlerContext ctx) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) //flush掉全部写回的数据 .addListener(ChannelFutureListener.CLOSE); //当flush完毕后关闭channel } public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) { cause.printStackTrace();//捕捉异常信息 ctx.close();//出现异常时关闭channel } }
package NettyDemo.echo.client; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; 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; import java.net.InetSocketAddress; import NettyDemo.echo.handler.EchoClientHandler; public class EchoClient { private final String host; private final int port; public EchoClient(String host, int port) { this.host = host; this.port = port; } public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group); b.channel(NioSocketChannel.class); b.remoteAddress(new InetSocketAddress(host, port)); b.handler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoClientHandler()); } }); ChannelFuture f = b.connect().sync(); f.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if(future.isSuccess()){ System.out.println("client connected"); }else{ System.out.println("server attemp failed"); future.cause().printStackTrace(); } } }); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } } public static void main(String[] args) throws Exception { new EchoClient("127.0.0.1", 3331).start(); } }1. 创建一个ServerBootstrap实例
package NettyDemo.echo.handler; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.ChannelHandler.Sharable; import io.netty.util.CharsetUtil; @Sharable public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> { /** *此方法会在连接到server后被调用 * */ public void channelActive(ChannelHandlerContext ctx) { ctx.write(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8)); } /** *此方法会在接收到server数据后调用 * */ public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) { System.out.println("Client received: " + ByteBufUtil.hexDump(in.readBytes(in.readableBytes()))); } /** *捕捉到异常 * */ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
标签:style blog http io os ar java strong sp
原文地址:http://www.cnblogs.com/lcchuguo/p/4025225.html