Java NIO 由以下几个核心部分组成:
Channels
Buffers
Selectors
此系列的文章参考并发变成网的内容 http://ifeve.com/overview/
还有我同事写的几篇文章 https://www.jianshu.com/p/12c81abb5387
下面是socket通信的例子
public static class ClientSocket implements Runnable {
public void run() {
try {
//SocketChannel的打开方式
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));
String newData = "New String to write to file..." + System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(48);//分配48字节capacity的ByteBuffer
buf.clear();//情况buffer,进行写入
buf.put(newData.getBytes());//buffer添加内容
buf.flip();//执行此方法,使buffer进入读状态
while (buf.hasRemaining()) {//判断buffer是不是读取完
socketChannel.write(buf);//将buffer内容读取到channel中
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static class ServerSocket implements Runnable {
public void run() {
ServerSocketChannel serverSocketChannel;
try {
serverSocketChannel = ServerSocketChannel.open();//打开socket服务端
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
//ServerSocketChannel可以设置成非阻塞模式。在非阻塞模式下,accept() 方法会立刻返回,如果还没有新进来的连接,返回的将是null
//serverSocketChannel.configureBlocking(false);
while (true) {
//监听新进来的连接
SocketChannel socketChannel = serverSocketChannel.accept();
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = socketChannel.read(buf);将通道信息写入buffer
while (bytesRead != -1) {//读取buffer
System.out.println("Read " + bytesRead);
buf.flip();
while (buf.hasRemaining()) {
System.out.print((char) buf.get());
}
buf.clear();
bytesRead = socketChannel.read(buf);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}