標籤: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