Netty完成网络通信(二)
生活随笔
收集整理的這篇文章主要介紹了
Netty完成网络通信(二)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Netty是基于NIO的框架,完善了NIO的一些缺陷,因此可以用Netty替代NIO
?
Netty實現通信步驟:
1、創建兩個NIO線程組,一個專門用于網絡事件處理(接受客戶端的連接),另一個則進行網絡通信讀寫。
2、創建一個ServerBootstrap對象,配置Netty的一系列參數,例如接受傳出數據的緩存大小等等。
3、創建一個實際處理數據的類ChannelInitializer,進行初始化的準備工作,比如設置接受傳出數據的字符集、格式、以及實際處理數據的接口。
4、綁定端口、執行同步阻塞方法等待服務器端啟動即可。
?
?
基于上一章的例子,現在用Netty寫一個服務端,替代上一章中NIO寫的服務端
?
服務端代碼
?
?1、公共部分
基本長的差不多
package com.zit;import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel;public class NettyServer {private int port;public NettyServer(int port) {this.port = port;}public void run() {/**** NioEventLoopGroup 是用來處理I/O操作的多線程事件循環器,* Netty提供了許多不同的EventLoopGroup的實現用來處理不同傳輸協議。 在這個例子中我們實現了一個服務端的應用,* 因此會有2個NioEventLoopGroup會被使用。 第一個經常被叫做‘boss’,用來接收進來的連接。* 第二個經常被叫做‘worker’,用來處理已經被接收的連接, 一旦‘boss’接收到連接,就會把連接信息注冊到‘worker’上。* 如何知道多少個線程已經被使用,如何映射到已經創建的Channels上都需要依賴于EventLoopGroup的實現,* 并且可以通過構造函數來配置他們的關系。*/EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();System.out.println("準備運行端口:" + port);/*** ServerBootstrap 是一個啟動NIO服務的輔助啟動類 你可以在這個服務中直接使用Channel*/try {ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup)//指定使用NioServerSocketChannel產生一個Channel用來接收連接.channel(NioServerSocketChannel.class)/**** 這里的事件處理類經常會被用來處理一個最近的已經接收的Channel。 ChannelInitializer是一個特殊的處理類,* 他的目的是幫助使用者配置一個新的Channel。* 也許你想通過增加一些處理類比如NettyServerHandler來配置一個新的Channel* 或者其對應的ChannelPipeline來實現你的網絡程序。 當你的程序變的復雜時,可能你會增加更多的處理類到pipline上,* 然后提取這些匿名類到最頂層的類上。*/.childHandler(new ChannelInitializer<SocketChannel>() {public void initChannel(SocketChannel ch) throws Exception {//ChannelPipeline用于存放管理ChannelHandel//ChannelHandler用于處理請求響應的業務邏輯相關代碼ch.pipeline().addLast(new ServerHandle());}}).option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();} finally {workerGroup.shutdownGracefully();bossGroup.shutdownGracefully();}}public static void main(String[] args) {//端口int port = 8888;new NettyServer(port).run();}}?
?
?2、處理部分
在這里更改處理數據的邏輯即可
?
package com.zit;import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.ReferenceCountUtil;public class ServerHandle extends ChannelInboundHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{try {ByteBuf in = (ByteBuf) msg;byte[] req = new byte[in.readableBytes()];in.readBytes(req);String body = new String(req,"utf-8");System.out.println("Server :" + body );String response = "返回給客戶端的響應:" + body ;ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));} finally {/*** ByteBuf是一個引用計數對象,這個對象必須顯示地調用release()方法來釋放。* 請記住處理器的職責是釋放所有傳遞到處理器的引用計數對象。*/// 拋棄收到的數據 ReferenceCountUtil.release(msg);}}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {/*** exceptionCaught() 事件處理方法是當出現 Throwable 對象才會被調用,即當 Netty 由于 IO* 錯誤或者處理器在處理事件時拋出的異常時。在大部分情況下,捕獲的異常應該被記錄下來 并且把關聯的 channel* 給關閉掉。然而這個方法的處理方式會在遇到不同異常的情況下有不 同的實現,比如你可能想在關閉連接之前發送一個錯誤碼的響應消息。*/// 出現異常就關閉 cause.printStackTrace();ctx.close();} }?
?
客戶端代碼:
和上一章的一模一樣,是為了證明Netty可以替代NIO完成服務端的處理
package com.zit;import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set;public class NIOClient {/*標識數字*/ private static int flag = 0; /*緩沖區大小*/ private static int BLOCK = 4096; /*接受數據緩沖區*/ private static ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK); /*發送數據緩沖區*/ private static ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK); /*服務器端地址*/ private final static InetSocketAddress SERVER_ADDRESS = new InetSocketAddress("127.0.0.1", 8888); public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // 打開socket通道 SocketChannel socketChannel = SocketChannel.open(); // 設置為非阻塞方式 socketChannel.configureBlocking(false); // 打開選擇器 Selector selector = Selector.open(); // 注冊連接服務端socket動作 socketChannel.register(selector, SelectionKey.OP_CONNECT); // 連接 socketChannel.connect(SERVER_ADDRESS); // 分配緩沖區大小內存 Set<SelectionKey> selectionKeys; Iterator<SelectionKey> iterator; SelectionKey selectionKey; SocketChannel client; String receiveText; String sendText; int count=0; while (true) { //選擇一組鍵,其相應的通道已為 I/O 操作準備就緒。 //此方法執行處于阻塞模式的選擇操作。 selector.select(); //返回此選擇器的已選擇鍵集。 selectionKeys = selector.selectedKeys(); //System.out.println(selectionKeys.size()); iterator = selectionKeys.iterator(); while (iterator.hasNext()) { selectionKey = iterator.next(); if (selectionKey.isConnectable()) { System.out.println("client connect"); client = (SocketChannel) selectionKey.channel(); // 判斷此通道上是否正在進行連接操作。 // 完成套接字通道的連接過程。 if (client.isConnectionPending()) { client.finishConnect(); System.out.println("完成連接!"); sendbuffer.clear(); sendbuffer.put("Hello,Server".getBytes()); sendbuffer.flip(); client.write(sendbuffer); } client.register(selector, SelectionKey.OP_READ); } else if (selectionKey.isReadable()) { client = (SocketChannel) selectionKey.channel(); //將緩沖區清空以備下次讀取 receivebuffer.clear(); //讀取服務器發送來的數據到緩沖區中 count=client.read(receivebuffer); if(count>0){ receiveText = new String( receivebuffer.array(),0,count); System.out.println("客戶端接受服務器端數據--:"+receiveText); client.register(selector, SelectionKey.OP_WRITE); } } else if (selectionKey.isWritable()) { sendbuffer.clear(); client = (SocketChannel) selectionKey.channel(); sendText = "message from client--" + (flag++); sendbuffer.put(sendText.getBytes()); //將緩沖區各標志復位,因為向里面put了數據標志被改變要想從中讀取數據發向服務器,就要復位 sendbuffer.flip(); client.write(sendbuffer); System.out.println("客戶端向服務器端發送數據--:"+sendText); client.register(selector, SelectionKey.OP_READ); } } selectionKeys.clear(); } } }?
運行效果:
?
轉載于:https://www.cnblogs.com/Donnnnnn/p/9488030.html
總結
以上是生活随笔為你收集整理的Netty完成网络通信(二)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TIME定时器
- 下一篇: webpack-plugin-webpa