一段简单的模拟服务器的代码(Selector)

public static void main(String[] args) throws Exception{

		int ports[]={8000,8001,8002,8003,8004};
		Selector selector = Selector.open();
		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]+"端口监听。");
			
		}
		while((selector.select())>0){
			Set<SelectionKey> selectedKeys = selector.selectedKeys();
			Iterator<SelectionKey> iter = selectedKeys.iterator();
			while(iter.hasNext()){
				SelectionKey key = iter.next();
				if(key.isAcceptable()){
					ServerSocketChannel server = (ServerSocketChannel)key.channel();
					SocketChannel client = server.accept();
					client.configureBlocking(false);
					ByteBuffer outBuf = ByteBuffer.allocate(1024);
					outBuf.put(("当前的时间为:"+new Date()).getBytes());
					outBuf.flip();
					client.write(outBuf);
					client.write(outBuf);
					client.close();
				}
			}
			
		}

你可能感兴趣的:(一段简单的模拟服务器的代码(Selector))