@Test
public void client() throws IOException {
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9897));
FileChannel fileChannel = FileChannel.open(Paths.get("D:\\1.png"), StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
while(fileChannel.read(buffer)!=-1) {
buffer.flip();
socketChannel.write(buffer);
buffer.clear();
}
socketChannel.close();
fileChannel.close();
}
@Test
public void server() throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(9897));
SocketChannel socketChannel = serverSocketChannel.accept();
FileChannel fileChannel = FileChannel.open(Paths.get("D:\\socket.png"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
while(socketChannel.read(buffer)!=-1) {
buffer.flip();
fileChannel.write(buffer);
buffer.clear();
}
fileChannel.close();
socketChannel.close();
serverSocketChannel.close();
}