Java新IO】_Selector

來源:互聯網
上載者:User

標籤:exception   figure   add   gis   設定   get   ++   class   iterator   

DateServer.java


import java.net.InetSocketAddress ;
import java.net.ServerSocket ;
import java.util.Set ;
import java.util.Iterator ;
import java.util.Date ;
import java.nio.channels.ServerSocketChannel ;
import java.nio.ByteBuffer ;
import java.nio.channels.SocketChannel ;
import java.nio.channels.Selector  ;
import java.nio.channels.SelectionKey  ;
public class DateServer{
    public static void main(String args[]) throws Exception {
        int ports[] = {8000,8001,8002,8003,8005,8006} ; // 表示五個監聽連接埠
        Selector selector = Selector.open() ;    // 通過open()方法找到Selector
        for(int i=0;i<ports.length;i++){
            ServerSocketChannel initSer = null ;
            initSer = ServerSocketChannel.open() ;    // 開啟伺服器的通道
            initSer.configureBlocking(false) ;    // 伺服器配置為非阻塞
            ServerSocket initSock = initSer.socket() ;
            InetSocketAddress address = null ;
            address = new InetSocketAddress(ports[i]) ;    // 執行個體化綁定地址
            initSock.bind(address) ;    // 進行服務的綁定
            initSer.register(selector,SelectionKey.OP_ACCEPT) ;    // 等待串連
            System.out.println("伺服器運行,在" + ports[i] + "連接埠監聽。") ;
        }
        // 要接收全部產生的key,並通過串連進行判斷是否擷取用戶端的輸出
        int keysAdd = 0 ;
        while((keysAdd=selector.select())>0){    // 選擇一組鍵,並且相應的通道已經準備就緒
            Set<SelectionKey> selectedKeys = selector.selectedKeys() ;// 取出全部產生的key
            Iterator<SelectionKey> iter = selectedKeys.iterator() ;
            while(iter.hasNext()){
                SelectionKey key = iter.next() ;    // 取出每一個key
                if(key.isAcceptable()){
                    ServerSocketChannel server = (ServerSocketChannel)key.channel() ;
                    SocketChannel client = server.accept() ;    // 接收新串連
                    client.configureBlocking(false) ;// 配置為非阻塞
                    ByteBuffer outBuf = ByteBuffer.allocateDirect(1024) ;    //
                    outBuf.put(("當前的時間為:" + new Date()).getBytes()) ;    // 向緩衝區中設定內容
                    outBuf.flip() ;
                    client.write(outBuf) ;    // 輸出內容
                    client.close() ;    // 關閉
                }
            }
            selectedKeys.clear() ;    // 清楚全部的key
        }
        
    }
}

Java新IO】_Selector

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.