簡單的NettyDemo-服務端


服務端

 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 }

結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM