项目需求需要在服务端实现一个阻塞IO,即netty发送完数据之后需要阻塞线程,直到有数据返回
@Test
public void client(){
try {
//1.获取通道
SocketChannel clientChannel = SocketChannel.open(
new InetSocketAddress("127.0.0.1", 7979));
System.out.println("client is start connecting...");
FileChannel fileChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
//2.分配指定大小的缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
//3.读取本地文件,并向服务端发送文件
while(fileChannel.read(buffer)!=-1){
buffer.flip();
clientChannel.write(buffer);
buffer.clear();
}
clientChannel.shutdownOutput();//告诉服务端数据已经发送完毕,否则客户端和服务端都会处于阻塞状态
//4.接收服务端的反馈
int len = 0;
while((len = clientChannel.read(buffer))!=-1){
buffer.flip();
System.out.println(new String(buffer.array(),0,len));
buffer.clear();
}
//5.关闭通道
clientChannel.close();
fileChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void server(){
try {
//1.获取通道
ServerSocketChannel serverChannel = ServerSocketChannel.open();
FileChannel outChannel = FileChannel.open(
Paths.get("bio.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
//2.绑定端口
serverChannel.bind(new InetSocketAddress(7979));
System.out.println("Server start in port:7979...");
//3.获取客户端连接
SocketChannel socketChannel = serverChannel.accept();
//4分配指定到小的缓冲区
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//5.读取数据
while (socketChannel.read(byteBuffer)!=-1){
byteBuffer.flip();
outChannel.write(byteBuffer);
byteBuffer.clear();
}
//6.发送反馈给客户端
byteBuffer.put("服务端接收数据成功!".getBytes());
byteBuffer.flip();
socketChannel.write(byteBuffer);
//7.关闭通道
socketChannel.close();
outChannel.close();
serverChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}