物聯網之路-啟航-1

物聯網之路-啟航-1

昨天我們整了個服務端的思路以及代碼,今給大家整個客戶端實例,在之前的項目經驗中,客戶端的創建是及其重要,特別是多客戶端的創建,

// Bootstrap,且構造函數變化很大,這裡用無參構造。
Bootstrap bootstrap = new Bootstrap();
// 指定channel[通道]類型
bootstrap.channel(NioSocketChannel.class);
// 指定Handler [操縱者]
bootstrap.handler(new ChannelInitializer<channel>() {

@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();

/*
* 這個地方的 必須和服務端對應上。否則無法正常解碼和編碼
*
*/
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());

// 客戶端的邏輯,自己對數據處理
pipeline.addLast(new HelloClientHandler());
}
});
// 指定EventLoopGroup [事件 組]
bootstrap.group(new NioEventLoopGroup());

// 連接到本地的8000端口的服務端
bootstrap.connect(new InetSocketAddress("127.0.0.1", 8000));


HelloClientHandler 類

/**
* 客戶端的邏輯,自己對數據處理
*
* @author flm
* 2017年11月10日
*/
private static class HelloClientHandler extends ChannelInboundHandlerAdapter {

/*
* 監聽 服務器 發送來的數據
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

System.out.println("Server say : " + msg.toString());

}

/*
* 啟動客戶端 時觸發
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Client active ");
ctx.writeAndFlush("我是 client " + new Date() + "\\n");
super.channelActive(ctx);
}

/*
* 關閉 客戶端 觸發
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Client close ");
super.channelInactive(ctx);
}
}

總結:客戶端以服務端的創建差別在於 Bootstrap 和 serverBootstrap 以及客戶端是需要添加IP的這樣客戶端才知道往哪裡發送唄/<channel>


分享到:


相關文章: