/**
* 客户端接收服务端的反馈
*/
public class TestBlockingNio2 {
/**
* 客户端
*/
@Test
public void client() throws IOException {
SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
FileChannel inChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (inChannel.read(buffer) != -1) {
buffer.flip();
sChannel.write(buffer);
buffer.clear();
}
//告诉服务端发送完毕
sChannel.shutdownOutput();
int len = 0;
//接收服务端的反馈
//从通道中读取数据
while ((len=sChannel.read(buffer)) != -1) {
buffer.flip();
System.out.println(new String(buffer.array(), 0, len));
buffer.clear();
}
inChannel.close();
sChannel.close();
}
/**
* 服务端
*/
@Test
public void server() throws IOException {
ServerSocketChannel ssChannel = ServerSocketChannel.open();
FileChannel outChannel = FileChannel.open(Paths.get("3.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
ssChannel.bind(new InetSocketAddress(9898));
SocketChannel sChannel = ssChannel.accept();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (sChannel.read(buffer) != -1) {
buffer.flip();
outChannel.write(buffer);
buffer.clear();
}
buffer.put("server接收成功".getBytes());
buffer.flip();
sChannel.write(buffer);
sChannel.close();
outChannel.close();
ssChannel.close();
}
}