物聯網之路-啟航-1

物聯網之路-啟航-1

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

// Bootstrap,且建構函式變化很大,這裡用無參構造。 Bootstrap bootstrap = new Bootstrap(); // 指定channel[通道]型別 bootstrap。channel(NioSocketChannel。class); // 指定Handler [操縱者] bootstrap。handler(new ChannelInitializer() { @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的這樣客戶端才知道往哪裡傳送唄