码迷,mamicode.com
首页 > 其他好文 > 详细

利用NIO的Selector处理服务器-客户端模型

时间:2015-05-05 00:04:06      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:

内容:这是一个简单的服务器-客户端模型,利用了NIO的Selector来处理多个管道。至于Selector的介绍看这里

NIOServer:

public class NIOServer {
	public static void main(String[] args) throws IOException, InterruptedException {
		Selector selector = Selector.open();
		
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), 8080);
		serverSocketChannel.socket().bind(address);
		serverSocketChannel.configureBlocking(false);
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		
		while (true) {
			if (selector.select() > 0) {
				Set<SelectionKey> selectionKeys = selector.selectedKeys();
				Iterator<SelectionKey> it = selectionKeys.iterator();
				while (it.hasNext()) {
					SelectionKey selectionKey = it.next();
					if (selectionKey.isAcceptable()) {
						serverSocketChannel = (ServerSocketChannel)selectionKey.channel();
						SocketChannel socketChannel = serverSocketChannel.accept();
						socketChannel.configureBlocking(false);
						socketChannel.register(selector, SelectionKey.OP_READ);
						System.out.println("Connected: " + socketChannel.socket().getRemoteSocketAddress());
					} else if (selectionKey.isReadable()) {
						SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
						ByteBuffer buffer = ByteBuffer.allocate(1024);
						while (socketChannel.read(buffer) > 0) {
							buffer.flip();
							byte[] dis = new byte[buffer.limit()]; 
							buffer.get(dis);
							System.out.println(new String(dis));
						}
					}
					
					it.remove();
				}
			}
			
			Thread.sleep(100);
		}
	}
}

NIOClient:

public class NIOClient {
	public static void main(String[] args) throws IOException {
		SocketChannel socketChannel = SocketChannel.open();
		InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), 8080);
		socketChannel.socket().connect(address);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		while (true) {
				try {
					buffer.clear();
					String time = sdf.format(new Date());
					buffer.put(time.getBytes());
					buffer.flip();
					socketChannel.write(buffer);
					Thread.sleep(5000);
				} catch (Exception e) {
					System.out.println("Connection Close");
					break;
				}
		}
	}
}


利用NIO的Selector处理服务器-客户端模型

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/45489029

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!