JAVA nio 学习笔记

闲着没事学习了一下nio 其中的内容还挺多。

总结:

1、开selector

2、开通道->设置非阻塞

3、实例化地址

4、得socket

5、socket绑定地址

6、监听注册

------------------------------------------------无敌分割

7、获得select

8、获得所有的key

9、获得服务器通道

10、获得客户端通道

11、实例化buffer

12、filp

13、写

14、关client通道

15、消key

 

import java.net.InetSocketAddress;
import java.net.ServerSocket;
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 NioServer {

	public static void main(String[] args) throws Exception{
		int posts[] = {8000,8001,8002,8003,8005,8006};
		Selector selector = Selector.open();
		for(int i = 0;i0) {
			Set setKey = selector.selectedKeys();
			Iterator itkey = setKey.iterator();
			while (itkey.hasNext()) {
				SelectionKey key = itkey.next() ;
				if(key.isAcceptable()){
					ServerSocketChannel dossc = (ServerSocketChannel) key.channel();
					SocketChannel clientChannel = dossc.accept();
					clientChannel.configureBlocking(false);
					ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
					buffer.put(("时间是"+new Date().toString()).getBytes());
					buffer.flip();
					clientChannel.write(buffer);
					clientChannel.close() ;	// 关闭
//					dossc.configureBlocking(false);
				}
			}
			setKey.clear();
			 
		}
	}
}

 

你可能感兴趣的:(java,j2ee)