我正在使用套接字编写客户端服务器,文件传输工作但文件不超过 64 KB,为什么会这样以及如何处理它?
服务器
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket servsock = new ServerSocket(4444);
File myFile = new File("D:\\Games\\Dog.mp3");
long len = myFile.length();
System.out.print(len);
while (true) {
Socket sock = servsock.accept();
byte[] mybytearray = new byte[(int) myFile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
sock.close();
}
}
}
客户
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
public class Client {
public static void main(String[] argv) throws Exception {
Socket sock = new Socket("127.0.0.1", 4444);
byte[] mybytearray = new byte[50000000];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("D:\\Dog.mpe");
BufferedOutputStream bos = new BufferedOutputStream(fos);
System.out.println(mybytearray);
System.out.println(mybytearray.length);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
sock.close();
}
}
正如您在评论中已经回答的那样,读取数据必须循环完成,手动控制所有内容。
服务器
客户
备择方案:
Apache CommonsIO
谷歌番石榴
byte[] bytes = ByteStreams.toByteArray(inputStream);