方法阻塞,方法一直阻塞,意味着這個程序卡在這里,一直不向下運行。知道這個阻塞方法執行完畢,有返回值。程序才繼續向下執行


方法阻塞,方法一直阻塞,意味着這個程序卡在這里,一直不向下運行。知道這個阻塞方法執行完畢,有返回值。程序才繼續向下執行.

  1.   while (true) {  
  2.             // 當注冊事件到達時,方法返回,否則該方法會一直阻塞  
  3.             selector.select();  //這里將一直阻塞,程序不會向下執行。直到這個方法執行完,有返回值后

 

2.// 采用輪詢的方式監聽selector上是否有需要處理的事件,如果有,則進行處理 

NIO SERVER
NIO SERVER
package com.anders.selector; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set;
public class NIOServer { // 通道管理器 private Selector selector; public void initServer(int port) throws Exception { // 獲得一個ServerSocket通道 ServerSocketChannel serverChannel = ServerSocketChannel.open(); // 設置通道為 非阻塞 serverChannel.configureBlocking(false); // 將該通道對於的serverSocket綁定到port端口 serverChannel.socket().bind(new InetSocketAddress(port)); // 獲得一耳光通道管理器 this.selector = Selector.open(); // 將通道管理器和該通道綁定,並為該通道注冊selectionKey.OP_ACCEPT事件 // 注冊該事件后,當事件到達的時候,selector.select()會返回, // 如果事件沒有到達selector.select()會一直阻塞 serverChannel.register(selector, SelectionKey.OP_ACCEPT); } // 采用輪訓的方式監聽selector上是否有需要處理的事件,如果有,進行處理 public void listen() throws Exception { System.out.println("start server"); // 輪詢訪問selector while (true) { // 當注冊事件到達時,方法返回,否則該方法會一直阻塞 selector.select(); // 獲得selector中選中的相的迭代器,選中的相為注冊的事件 Iterator ite = this.selector.selectedKeys().iterator(); while (ite.hasNext()) { SelectionKey key = (SelectionKey) ite.next(); // 刪除已選的key 以防重負處理 ite.remove(); // 客戶端請求連接事件 if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); // 獲得和客戶端連接的通道 SocketChannel channel = server.accept(); // 設置成非阻塞 channel.configureBlocking(false); // 在這里可以發送消息給客戶端 channel.write(ByteBuffer.wrap(new String("hello client").getBytes())); // 在客戶端 連接成功之后,為了可以接收到客戶端的信息,需要給通道設置讀的權限 channel.register(this.selector, SelectionKey.OP_READ); // 獲得了可讀的事件 } else if (key.isReadable()) { read(key); } } } } // 處理 讀取客戶端發來的信息事件 private void read(SelectionKey key) throws Exception { // 服務器可讀消息,得到事件發生的socket通道 SocketChannel channel = (SocketChannel) key.channel(); // 穿件讀取的緩沖區 ByteBuffer buffer = ByteBuffer.allocate(10); channel.read(buffer); byte[] data = buffer.array(); String msg = new String(data).trim(); System.out.println("server receive from client: " + msg); ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes()); channel.write(outBuffer); } public static void main(String[] args) throws Throwable { NIOServer server = new NIOServer(); server.initServer(8989); server.listen(); } }

Client 

package com.anders.selector;  
  
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;  
  
public class NIOClient {  
  
    // 通道管理器  
    private Selector selector;  
  
    /** 
     * * // 獲得一個Socket通道,並對該通道做一些初始化的工作 * @param ip 連接的服務器的ip // * @param port 
     * 連接的服務器的端口號 * @throws IOException 
     */  
    public void initClient(String ip, int port) throws IOException { // 獲得一個Socket通道  
        SocketChannel channel = SocketChannel.open(); // 設置通道為非阻塞  
        channel.configureBlocking(false); // 獲得一個通道管理器  
        this.selector = Selector.open(); // 客戶端連接服務器,其實方法執行並沒有實現連接,需要在listen()方法中調  
        // 用channel.finishConnect();才能完成連接  
        channel.connect(new InetSocketAddress(ip, port));  
        // 將通道管理器和該通道綁定,並為該通道注冊SelectionKey.OP_CONNECT事件。  
        channel.register(selector, SelectionKey.OP_CONNECT);  
    }  
  
    /** 
     * * // 采用輪詢的方式監聽selector上是否有需要處理的事件,如果有,則進行處理 * @throws // IOException 
     * @throws Exception  
     */  
    @SuppressWarnings("unchecked")  
    public void listen() throws Exception { // 輪詢訪問selector  
        while (true) {  
            // 選擇一組可以進行I/O操作的事件,放在selector中,客戶端的該方法不會阻塞,  
            // 這里和服務端的方法不一樣,查看api注釋可以知道,當至少一個通道被選中時,  
            // selector的wakeup方法被調用,方法返回,而對於客戶端來說,通道一直是被選中的  
            selector.select(); // 獲得selector中選中的項的迭代器  
            Iterator ite = this.selector.selectedKeys().iterator();  
            while (ite.hasNext()) {  
                SelectionKey key = (SelectionKey) ite.next(); // 刪除已選的key,以防重復處理  
                ite.remove(); // 連接事件發生  
                if (key.isConnectable()) {  
                    SocketChannel channel = (SocketChannel) key.channel(); // 如果正在連接,則完成連接  
                    if (channel.isConnectionPending()) {  
     channel.finishConnect();  
                    } // 設置成非阻塞  
    channel.configureBlocking(false);  
                    // 在這里可以給服務端發送信息哦  
                    channel.write(ByteBuffer.wrap(new String("hello server!").getBytes()));  
                    // 在和服務端連接成功之后,為了可以接收到服務端的信息,需要給通道設置讀的權限。  
                    channel.register(this.selector, SelectionKey.OP_READ); // 獲得了可讀的事件  
                } else if (key.isReadable()) {  
                    read(key);  
                }  
            }  
        }  
    }  
  
    private void read(SelectionKey key) throws Exception {  
        SocketChannel channel = (SocketChannel) key.channel();  
        // 穿件讀取的緩沖區  
        ByteBuffer buffer = ByteBuffer.allocate(10);  

        channel.read(buffer);  
        byte[] data = buffer.array();  
        String msg = new String(data).trim();  
        System.out.println("client receive msg from server:" + msg);  
        ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());  
        channel.write(outBuffer);  
  
    }  
  
    /** 
     * * // 啟動客戶端測試 * @throws IOException 
     * @throws Exception  
     */  
    public static void main(String[] args) throws Exception {  
        NIOClient client = new NIOClient();  
        client.initClient("localhost", 8989);  
        client.listen();  
    }  
}  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM