我正在用java编写一个套接字程序,该程序应该通过将文件分成512字节的 block 来从客户端上传文件。但显然服务器没有将前 512 字节写入文件。 我的客户端代码
DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());
dOut.writeUTF(number);
dOut.flush(); // Send off the data
File myFile = new File(name);
byte[] mybytearray = new byte[512];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
OutputStream ostream = sock.getOutputStream();
//Sending file name and file size to the server
DataOutputStream dos = new DataOutputStream(ostream);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
int count;
while ((count = dis.read(mybytearray)) > 0) {
dos.write(mybytearray, 0, count);
}
dos.close();
dis.close();
我的服务器代码
DataInputStream dIn = new DataInputStream(clientSocket.getInputStream());
String number = dIn.readUTF();
File path = new File(Globals.rootPath+"/"+number);
if(!path.exists()) path.mkdir();
DataInputStream clientData = new DataInputStream(clientSocket.getInputStream());
String name = clientData.readUTF();
File outfile = new File(Globals.rootPath+"/"+number+"/"+name);
OutputStream output = new FileOutputStream(outfile);
long size = clientData.readLong();
byte[] buffer = new byte[512];
int count;
while ((count = dIn.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
output.close();
dIn.close();
我知道代码极其困惑,有很多不必要的东西。这是我第一次使用套接字,当我让它正常工作后我会清理它。
最佳答案
首先,您正在调用 dis.readFully(mybytearray, 0, mybytearray.length)
,但未使用该值,因此前 512 个字节将被丢弃。
接下来,您将在数据之前写入文件名 (writeUTF(...)
) 和数组长度 (writeLong(...)
),但是您仅读取文件名(readUTF()
),而不读取数组长度,因此数组长度的 8 个字节成为数据的前 8 个字节。
仅供引用: block 大小相对没有意义,因为客户端和服务器不必使用相同的 block 大小。这都是套接字中的数据流,套接字实现可能会缓冲并将流数据切割成更适合传输协议(protocol)(可能是以太网)的片段。
关于Java套接字文件上传到服务器,服务器不获取字节数组的第一个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33057516/