首页 > 其他 > 详细

nio-选择器

时间:2014-02-20 09:04:02      阅读:444      评论:0      收藏:0      [点我收藏+]
package UDPDemo;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

public class DateServer {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		//表示5个监听端口
		int []ports = new int[]{8001,8002,8003,8004,8005,8006};
		//通过open方法找到selector
		Selector selector = Selector.open();
		for(int i=0;i<ports.length;i++){
			//打开服务器的通道
			ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
			//设置服务器为非阻塞
			serverSocketChannel.configureBlocking(false);
			//实例化绑定地址,端口
			InetSocketAddress addr = new InetSocketAddress(ports[i]);
			//服务器开始监听地址
			serverSocketChannel.bind(addr);
			//注册等待事件
			serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
			System.out.println("服务器开始监听:"+ports[i]+" 端口");
			 
		}
		//要接收全部生成的key,并通过连接进行判断是否获取客户端的输出
		int keysAdd = 0;
		//选择一组键,并且相应的通道已经打开
		while((keysAdd = selector.select())>0){
			//取出全部的键
			Set<SelectionKey> selectionKeys = selector.selectedKeys() ;
			Iterator<SelectionKey> iterator = selectionKeys.iterator();
			while(iterator.hasNext()){
				SelectionKey key = iterator.next();
				if(key.isAcceptable()){
					//
					ServerSocketChannel server = (ServerSocketChannel) key.channel();//取得对应的服务器通道
					//获取客户端
					SocketChannel client =  server.accept(); 
					//设置非阻塞
					client.configureBlocking(false);
					ByteBuffer  bf = ByteBuffer.allocate(1024);
					bf.put(("当前时间为:"+new Date()).getBytes());
					bf.flip();
					client.write(bf);
					client.close();
				}
			}
			selectionKeys.clear();
			
		}

	}

}

nio-选择器

原文:http://blog.csdn.net/u013494310/article/details/19500359

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!