基於Netty5.0中級案例五之Netty與C#Socket收發字串進行通訊
阿新 • • 發佈:2018-12-13
- package com.itstack.netty;
- import java.nio.charset.Charset;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.handler.codec.LineBasedFrameDecoder;
- import io.netty.handler.codec.string.StringDecoder;
- import io.netty.handler.codec.string.StringEncoder;
- public class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
- @Override
- protected void initChannel(SocketChannel e) throws Exception {
- System.out.println("報告");
- System.out.println("資訊:有一客戶端連結到本服務端");
- System.out.println("IP:" + e.localAddress().getHostName());
- System.out.println("Port:" + e.localAddress().getPort());
- System.out.println("報告完畢");
- //字串類解析
- e.pipeline().addLast(new LineBasedFrameDecoder(1024));
- //設定解碼為UTF-8
- e.pipeline().addLast(new StringDecoder(Charset.forName("utf-8")));
- //設定編碼為UTF-8
- e.pipeline().addLast(new StringEncoder(Charset.forName("utf-8")));
- // 在管道中新增我們自己的接收資料實現方法
- e.pipeline().addLast(new MyServerHanlder());
- }
- }