使用NIO完成网络通信三个核心:
1.通道(Channel):负责连接
2.缓冲区(Buffer):负责数据存取
3.选择器(Selector):是SelectableChannel的多路复用器,用于监控SelectableChannel的I/O状况
FileChannel不能切换成非阻塞模式
阻塞式:
@Test
public void bioSocketClient() {
SocketChannel sChannel = null;
FileChannel fChannel = null;
try {
sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 7478));
fChannel = FileChannel.open(Paths.get("E:", "a.jpg"), StandardOpenOption.READ);
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while(fChannel.read(byteBuffer) != -1) {
byteBuffer.flip();
sChannel.write(byteBuffer);
byteBuffer.clear();
}
sChannel.shutdownOutput(); //告诉服务端发送完了,否则服务端会一直阻塞等待
int len = 0;
while((len = sChannel.read(byteBuffer)) != -1) {
System.out.println(new String(byteBuffer.array(), 0, len));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fChannel.close();
sChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void bioSocketServer() {
ServerSocketChannel ssChannel = null;
FileChannel fChannel = null;
try {
//获取通道
ssChannel = ServerSocketChannel.open();
//绑定连接
ssChannel.bind(new InetSocketAddress(7478));
fChannel = FileChannel.open(Paths.get("E:", "s.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
//获取客户端连接的通道
SocketChannel sChannel = ssChannel.accept();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while(sChannel.read(byteBuffer) != -1) {
byteBuffer.flip();
fChannel.write(byteBuffer);
byteBuffer.clear();
}
//发送反馈给客户端
byteBuffer.put("服务端接受成功".getBytes());
byteBuffer.flip();
sChannel.write(byteBuffer);
sChannel.shutdownOutput(); //告诉客户端发送完了,否则客户端会一直阻塞等待
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fChannel.close();
ssChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
TCP传输模式中,调用Socket的shutdownInput()和shutdownOutput()都做了些什么?
非阻塞式:
将通道注册到选择器上
@Test
public void bioSocketClient() {
SocketChannel sChannel = null;
FileChannel fChannel = null;
try {
//获取通道
sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 7478));
//切换非阻塞模式
sChannel.configureBlocking(false);
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String msg = scanner.next();
byteBuffer.put((LocalDateTime.now().toString() + "\n" + msg).getBytes());
byteBuffer.flip();
sChannel.write(byteBuffer);
byteBuffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
sChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void bioSocketServer() {
ServerSocketChannel ssChannel = null;
FileChannel fChannel = null;
try {
//获取通道
ssChannel = ServerSocketChannel.open();
ssChannel.configureBlocking(false);
//绑定连接
ssChannel.bind(new InetSocketAddress(7478));
//将通道注册到选择器上
Selector selector = Selector.open();
//并指定监听事件
ssChannel.register(selector, SelectionKey.OP_ACCEPT);
while (selector.select() > 0) {
//轮询获取选择器上已经就绪的事件
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey selectionKey = it.next();
if (selectionKey.isAcceptable()) {
//若“接收就绪”,获取客户端连接
SocketChannel sChannel = ssChannel.accept();
//切换非阻塞式
sChannel.configureBlocking(false);
//将该通道注册到选择器上
sChannel.register(selector, SelectionKey.OP_READ);
} else if (selectionKey.isReadable()) {
//获取当前选择器上读就绪状态的通道
SocketChannel sChannel = (SocketChannel) selectionKey.channel();
//读取数据
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int len = 0;
while ((len = sChannel.read(byteBuffer)) > 0) {
byteBuffer.flip();
System.out.println(new String(byteBuffer.array(), 0, len));
byteBuffer.clear();
}
}
//取消selectionKey
it.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ssChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
udp
@Test
public void datagramChannelSend() {
DatagramChannel openChannel = null;
try {
openChannel = DatagramChannel.open();
openChannel.configureBlocking(false);
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String msg = scanner.next();
byteBuffer.put((LocalDateTime.now() + "\n" + msg).getBytes());
byteBuffer.flip();
openChannel.send(byteBuffer, new InetSocketAddress("127.0.0.1", 7575));
byteBuffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
openChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void datagramChannelreceive() {
DatagramChannel openChannel = null;
try {
openChannel = DatagramChannel.open();
openChannel.configureBlocking(false);
openChannel.bind(new InetSocketAddress(7575));
Selector selector = Selector.open();
openChannel.register(selector, SelectionKey.OP_READ);
while(selector.select() > 0) {
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey selectionKey = it.next();
if(selectionKey.isReadable()) {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
openChannel.receive(byteBuffer);
byteBuffer.flip();
System.out.println(new String(byteBuffer.array(), 0, byteBuffer.limit()));
byteBuffer.clear();
}
}
it.remove();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
openChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}