@Test
public void client() throws IOException {
//获取通道
SocketChannel sChannel = SocketChannel .open(new InetSocketAddress("127.0.0.1", 8001));
FileChannel inChannel = FileChannel.open(Paths.get("d:/1.txt"), StandardOpenOption.READ);
//分配指定大小的缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
//读取本地文件发送到服务器端
while ((inChannel.read(buffer))!=-1) {
buffer.flip();
sChannel.write(buffer);
buffer.clear();
}
//关闭通道
inChannel.close();
sChannel.close();
}
//服务端
@Test
public void server() throws IOException {
//获取通道
ServerSocketChannel serverSocket = ServerSocketChannel.open();
FileChannel outChannel = FileChannel.open(Paths.get("d:/2.txt"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
//绑定链接
serverSocket.bind(new InetSocketAddress(8001));
//获取客户端连接的通道
SocketChannel socketChannel = serverSocket.accept();
//分配指定大小的缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
//读取客户端的数据并保存到本地
while ((socketChannel.read(buffer))!=-1) {
buffer.flip();
outChannel.write(buffer);
buffer.clear();
}
//关闭对应的通道
socketChannel.close();
outChannel.close();
serverSocket.close();
}