首先值得注意的是netty的jar包版本问题,版本不同,运用的方式也不同。我这里用4.0版本。
对于小白来说,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; /** * 服务器 */ public class NettyServer { private final int port = 8989; public static void main(String[] args) { new NettyServer().nettyServer(); } public void nettyServer(){ EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootStrap = new ServerBootstrap(); serverBootStrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChildChannelHandler()); ChannelFuture futrue = serverBootStrap.bind(port).sync(); futrue.channel().closeFuture().sync(); } catch (Exception e) { // TODO: handle exception } } private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{ @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new SimpleServerHandler()); } } }
import java.util.Scanner; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class SimpleServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ChannelManager.serverChannel = ctx; new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while(true){ Scanner sc = new Scanner(System.in); byte [] req = sc.nextLine().getBytes(); ByteBuf msg = Unpooled.buffer(req.length); msg.writeBytes(req); ChannelManager.serverChannel.writeAndFlush(msg); } } }).start(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; byte [] req = new byte[buf.readableBytes()]; buf.readBytes(req); String message = new String(req,"UTF-8"); System.out.println("server:"+message); } }
上述两个类实现netty的服务端,下面就是客户端啦
import io.netty.bootstrap.Bootstrap; 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.NioSocketChannel; public class NettyClient { public static void main(String[] args) { new NettyClient().connect(8989, "127.0.0.1"); } public void connect(int port, String host){ EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { // TODO Auto-generated method stub ch.pipeline().addLast(new SimpleClientHandler()); } }); ChannelFuture channelFuture = bootstrap.connect(host,port).sync(); channelFuture.channel().closeFuture().sync(); } catch (Exception e) { // TODO: handle exception } } }
import java.util.Scanner; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class SimpleClientHandler extends ChannelInboundHandlerAdapter { private ByteBuf clientMessage; public SimpleClientHandler(){ byte [] req = "call-user-service".getBytes(); clientMessage = Unpooled.buffer(req.length); clientMessage.writeBytes(req); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ChannelManager.clientChannel = ctx; new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while(true){ Scanner sc = new Scanner(System.in); byte [] req = sc.nextLine().getBytes(); ByteBuf msg = Unpooled.buffer(req.length); msg.writeBytes(req); ChannelManager.clientChannel.writeAndFlush(msg); } } }).start(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; byte [] req = new byte[buf.readableBytes()]; buf.readBytes(req); String message = new String(req,"UTF-8"); System.out.println("client:"+message); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }
好了,万事俱备,再添加一个ChannelManager.java netty的通道管理器
import io.netty.channel.ChannelHandlerContext; public class ChannelManager { public static ChannelHandlerContext serverChannel; public static ChannelHandlerContext clientChannel; }
这样就可以实现netty的前后端的控制台通讯了,代码解释就不进行了