真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

NIOSocket非阻塞模式是什么

本篇內(nèi)容主要講解“NIO Socket非阻塞模式是什么”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“NIO Socket非阻塞模式是什么”吧!

我們提供的服務(wù)有:成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站、微信公眾號(hào)開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、新北ssl等。為數(shù)千家企事業(yè)單位解決了網(wǎng)站和推廣的問(wèn)題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的新北網(wǎng)站制作公司

NIO主要原理和適用

NIO 有一個(gè)主要的類Selector,這個(gè)類似一個(gè)觀察者,只要我們把需要探知的socketchannel告訴Selector,我們接著做別的事情,當(dāng)有 事件發(fā)生時(shí),他會(huì)通知我們,傳回一組SelectionKey,我們讀取這些Key,就會(huì)獲得我們剛剛注冊(cè)過(guò)的socketchannel,然后,我們從 這個(gè)Channel中讀取數(shù)據(jù),放心,包準(zhǔn)能夠讀到,接著我們可以處理這些數(shù)據(jù)。

Selector內(nèi)部原理實(shí)際是在做一個(gè)對(duì)所注冊(cè)的channel的輪詢?cè)L問(wèn),不斷的輪詢(目前就這一個(gè)算法),一旦輪詢到一個(gè)channel有所注冊(cè)的事情發(fā)生,比如數(shù)據(jù)來(lái)了,他就會(huì)站起來(lái)報(bào)告,交出一把鑰匙,讓我們通過(guò)這把鑰匙來(lái)讀取這個(gè)channel的內(nèi)容。

jdk供的無(wú)阻塞I/O(NIO)有效解決了多線程服務(wù)器存在的線程開銷問(wèn)題,但在使用上略顯得復(fù)雜一些。在NIO中使用多線程,主要目的已不是為了應(yīng)對(duì) 每個(gè)客戶端請(qǐng)求而分配獨(dú)立的服務(wù)線程,而是通過(guò)多線程充分使用用多個(gè)CPU的處理能力和處理中的等待時(shí)間,達(dá)到提高服務(wù)能力的目的。

這段時(shí)間在研究NIO,寫篇博客來(lái)記住學(xué)過(guò)的東西。還是從最簡(jiǎn)單的Hello World開始,client多線程請(qǐng)求server端,server接收client的名字,并返回Hello! +名字的字符格式給client。當(dāng)然實(shí)際應(yīng)用并不這么簡(jiǎn)單,實(shí)際可能是訪問(wèn)文件或者數(shù)據(jù)庫(kù)獲取信息返回給client。非阻塞的NIO有何神秘之處?

代 碼:

1)server端代碼

public class HelloWorldServer {        static int BLOCK = 1024;       static String name = "";       protected Selector selector;       protected ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK);       protected CharsetDecoder decoder;       static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();        public HelloWorldServer(int port) throws IOException {           selector = this.getSelector(port);           Charset charset = Charset.forName("GB2312");           decoder = charset.newDecoder();       }        // 獲取Selector       protected Selector getSelector(int port) throws IOException {           ServerSocketChannel server = ServerSocketChannel.open();           Selector sel = Selector.open();           server.socket().bind(new InetSocketAddress(port));           server.configureBlocking(false);           server.register(sel, SelectionKey.OP_ACCEPT);           return sel;       }        // 監(jiān)聽端口       public void listen() {           try {               for (;;) {                   selector.select();                   Iterator iter = selector.selectedKeys().iterator();                   while (iter.hasNext()) {                       SelectionKey key = (SelectionKey) iter.next();                       iter.remove();                       process(key);                   }               }           } catch (IOException e) {               e.printStackTrace();           }       }        // 處理事件       protected void process(SelectionKey key) throws IOException {           if (key.isAcceptable()) { // 接收請(qǐng)求               ServerSocketChannel server = (ServerSocketChannel) key.channel();               SocketChannel channel = server.accept();               //設(shè)置非阻塞模式               channel.configureBlocking(false);               channel.register(selector, SelectionKey.OP_READ);           } else if (key.isReadable()) { // 讀信息               SocketChannel channel = (SocketChannel) key.channel();               int count = channel.read(clientBuffer);               if (count > 0) {                   clientBuffer.flip();                   CharBuffer charBuffer = decoder.decode(clientBuffer);                   name = charBuffer.toString();                   // System.out.println(name);                   SelectionKey sKey = channel.register(selector,                           SelectionKey.OP_WRITE);                   sKey.attach(name);               } else {                   channel.close();               }                clientBuffer.clear();           } else if (key.isWritable()) { // 寫事件               SocketChannel channel = (SocketChannel) key.channel();               String name = (String) key.attachment();                              ByteBuffer block = encoder.encode(CharBuffer                       .wrap("Hello !" + name));                               channel.write(block);                //channel.close();            }       }        public static void main(String[] args) {           int port = 8888;           try {               HelloWorldServer server = new HelloWorldServer(port);               System.out.println("listening on " + port);                              server.listen();                          } catch (IOException e) {               e.printStackTrace();           }       }   }

2)client端代碼

public class HelloWorldClient {        static int SIZE = 10;       static InetSocketAddress ip = new InetSocketAddress("localhost", 8888);       static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();        static class Message implements Runnable {           protected String name;           String msg = "";            public Message(String index) {               this.name = index;           }            public void run() {               try {                   long start = System.currentTimeMillis();                   //打開Socket通道                   SocketChannel client = SocketChannel.open();                   //設(shè)置為非阻塞模式                   client.configureBlocking(false);                   //打開選擇器                   Selector selector = Selector.open();                   //注冊(cè)連接服務(wù)端socket動(dòng)作                   client.register(selector, SelectionKey.OP_CONNECT);                   //連接                   client.connect(ip);                   //分配內(nèi)存                   ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);                   int total = 0;                    _FOR: for (;;) {                       selector.select();                       Iterator iter = selector.selectedKeys().iterator();                        while (iter.hasNext()) {                           SelectionKey key = (SelectionKey) iter.next();                           iter.remove();                           if (key.isConnectable()) {                               SocketChannel channel = (SocketChannel) key                                       .channel();                               if (channel.isConnectionPending())                                   channel.finishConnect();                               channel                                       .write(encoder                                               .encode(CharBuffer.wrap(name)));                                channel.register(selector, SelectionKey.OP_READ);                           } else if (key.isReadable()) {                               SocketChannel channel = (SocketChannel) key                                       .channel();                               int count = channel.read(buffer);                               if (count > 0) {                                   total += count;                                   buffer.flip();                                    while (buffer.remaining() > 0) {                                       byte b = buffer.get();                                       msg += (char) b;                                                                          }                                    buffer.clear();                               } else {                                   client.close();                                   break _FOR;                               }                           }                       }                   }                   double last = (System.currentTimeMillis() - start) * 1.0 / 1000;                   System.out.println(msg + "used time :" + last + "s.");                   msg = "";               } catch (IOException e) {                   e.printStackTrace();               }           }       }        public static void main(String[] args) throws IOException {                  String names[] = new String[SIZE];            for (int index = 0; index < SIZE; index++) {               names[index] = "jeff[" + index + "]";               new Thread(new Message(names[index])).start();           }              }   }

到此,相信大家對(duì)“NIO Socket非阻塞模式是什么”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!


分享標(biāo)題:NIOSocket非阻塞模式是什么
URL標(biāo)題:http://weahome.cn/article/ipppji.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部