既然是入门,那我们就在这里写一个简单的Demo,客户端发送一个字符串到服务器端,服务器端接收字符串后再发送回客户端。
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> { /** *此方法会在连接到服务器后被调用 * */ public void channelActive(ChannelHandlerContext ctx) { ctx.write(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8)); } /** *此方法会在接收到服务器数据后调用 * */ 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(); } }
Netty入门二:开发第一个Netty应用程序,布布扣,bubuko.com
原文:http://blog.csdn.net/suifeng3051/article/details/25238243