前言: 在linux 中 transferTo 方法就可以完成传输,在 windows 中依次调用transferTo最多能传8M文件,需要分段传文件,而且要注意传输起点位置
模拟服务端实验源码:
package com.dev.nio.TRANSFERTO;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class IOServer {
public static void main(String[] args) throws Exception {
InetSocketAddress address = new InetSocketAddress(7001);
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
ServerSocket serverSocket = serverSocketChannel.socket();
serverSocket.bind(address);
ByteBuffer byteBuffer = ByteBuffer.allocate(4096);
while (true){
SocketChannel socketChannel = serverSocketChannel.accept();
int readcount = 0;
while (readcount!=-1){
try {
readcount = socketChannel.read(byteBuffer);
}catch (Exception e){
break;
}
byteBuffer.rewind();
}
}
}
}
模拟客户端实验源码:
package com.dev.nio.TRANSFERTO;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
public class clentServer {
public static void main(String[] args) throws Exception {
String fileName="d:\\1m.7z";
SocketChannel socketChannel = SocketChannel.open();
InetSocketAddress address = new InetSocketAddress("localhost", 7001);
socketChannel.connect(address);
FileChannel fileChannel = new FileInputStream(fileName).getChannel();
long startTime = System.currentTimeMillis();
long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);
System.out.println("发送的总字节数="+transferCount+" 耗时:"+(System.currentTimeMillis()-startTime));
socketChannel.close();
fileChannel.close();
}
}
实验结果:
|