Java网络编程之NIO编程(待补充)
学习网站1:http://ifeve.com/java-nio-all/
学习网站2:http://www.ibm.com/developerworks/cn/education/java/j-nio/j-nio.html
NIO案例1
package com.pc;
import java.io.IOException;
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.Iterator;
import java.util.Set;
/**
* Created by Switch on 2016/3/19.
* 测试NIO
*/
public class TestNIO1 {
/**
* NIO使用案例
*
* @throws IOException
*/
public void selector() throws IOException {
// 创建字节缓冲区,并分配字节缓冲区大小
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 创建选择器
Selector selector = Selector.open();
// 创建服务器套接字通道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 配置Channel为非阻塞模式
serverSocketChannel.configureBlocking(false);
// 获得和Channel关联的Service Socket,并绑定端口
serverSocketChannel.socket().bind(new InetSocketAddress(8888));
// Channel注册选择器和选择器键
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
// 监测注册在选择器上的所有通信信道是否有需要的事件发生
while (true) {
// 返回此选择器的已选择键集
Set selectedKeys = selector.selectedKeys();
Iterator iterator = selectedKeys.iterator();
// 迭代访问键集
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) iterator.next();
// 值是OP_ACCEPT
if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
// 返回创建此键的通道
ServerSocketChannel ssChannel = (ServerSocketChannel) key.channel();
// 接受到此通道套接字的连接
SocketChannel sc = ssChannel.accept();
sc.configureBlocking(false);
// Channel注册选择器和选择器键
sc.register(selector, SelectionKey.OP_READ);
// 从键集中移除该键
iterator.remove();
} else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
// 值是OP_READ
// 返回创建此键的通道
SocketChannel sc = (SocketChannel) key.channel();
while (true) {
buffer.clear();
// 读取数据
int n = sc.read(buffer);
if (n <= 0) {
break;
}
// 将limit设置为当前位置,然后将position设置为 0
buffer.flip();
}
// 从键集中移除该键
iterator.remove();
}
}
}
}
}
来源:CSDN
作者:Switchvov
链接:https://blog.csdn.net/q547550831/article/details/50933424