服务端
1 public class Server { 2 public static void main(String[] args) { 3 //设置Server客户端 4 ServerBootstrap bootstrap = new ServerBootstrap(); 5 6 //设置线程池 7 ExecutorService boss = Executors.newCachedThreadPool(); 8 ExecutorService worker = Executors.newCachedThreadPool(); 9 10 //设置nioSocket工厂 11 bootstrap.setFactory(new NioServerSocketChannelFactory(boss, worker)); 12 13 //设置管道 14 bootstrap.setPipelineFactory(new ChannelPipelineFactory() { 15 //在管道里添加拦截器 16 @Override 17 public ChannelPipeline getPipeline() throws Exception { 18 ChannelPipeline pipeline = Channels.pipeline(); 19 pipeline.addLast("decoder", new StringDecoder()); 20 pipeline.addLast("encoder", new StringEncoder()); 21 pipeline.addLast("helloHandler", new HelloHandler()); 22 return pipeline; 23 } 24 }); 25 //监听10010端口 26 bootstrap.bind(new InetSocketAddress(10010)); 27 28 System.out.println("服务端启动"); 29 30 } 31 }
Hellohandler
1 public class HelloHandler extends SimpleChannelHandler { 2 3 /** 4 * 接收消息 5 */ 6 @Override 7 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { 8 System.out.println("messageReceived" +e); 9 System.out.println("客户端发来消息:" + e.getMessage()); 10 //回写数据 11 Channel channel = e.getChannel(); 12 channel.write("hi"); 13 super.messageReceived(ctx, e); 14 15 16 } 17 /** 18 * 关闭链接 19 */ 20 @Override 21 public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { 22 System.out.println("channelClosed" +e); 23 super.channelClosed(ctx, e); 24 } 25 26 /** 27 * 建立连接 28 */ 29 @Override 30 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { 31 System.out.println("channelConnected" +e); 32 super.channelConnected(ctx, e); 33 } 34 /** 35 * 关闭连接 清除缓存 36 */ 37 @Override 38 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { 39 System.out.println("channelDisconnected" +e); 40 super.channelDisconnected(ctx, e); 41 } 42 /** 43 * 捕获异常 44 */ 45 @Override 46 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { 47 System.out.println("exceptionCaught" +e); 48 super.exceptionCaught(ctx, e); 49 } 50 51 52 }
结果: