1. 程式人生 > >基於Netty5.0中級案例五之Netty與C#Socket收發字串進行通訊

基於Netty5.0中級案例五之Netty與C#Socket收發字串進行通訊

  1. package com.itstack.netty;
  2. import java.nio.charset.Charset;
  3. import io.netty.channel.ChannelInitializer;
  4. import io.netty.channel.socket.SocketChannel;
  5. import io.netty.handler.codec.LineBasedFrameDecoder;
  6. import io.netty.handler.codec.string.StringDecoder;
  7. import io.netty.handler.codec.string.StringEncoder;
  8. public class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
  9. @Override
  10. protected void initChannel(SocketChannel e) throws Exception {
  11. System.out.println("報告");
  12. System.out.println("資訊:有一客戶端連結到本服務端");
  13. System.out.println("IP:" + e.localAddress().getHostName());
  14. System.out.println("Port:" + e.localAddress().getPort());
  15. System.out.println("報告完畢");
  16. //字串類解析
  17. e.pipeline().addLast(new LineBasedFrameDecoder(1024));
  18. //設定解碼為UTF-8
  19. e.pipeline().addLast(new StringDecoder(Charset.forName("utf-8")));
  20. //設定編碼為UTF-8
  21. e.pipeline().addLast(new StringEncoder(Charset.forName("utf-8")));
  22. // 在管道中新增我們自己的接收資料實現方法
  23. e.pipeline().addLast(new MyServerHanlder());
  24. }
  25. }