Javasocket文件上载到服务器,服务器不获取字节数组的第一个字节
我正在用java编写一个socket程序,它应该通过将文件分成512字节的块来从客户端上传文件。但显然服务器并没有将前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();
我知道代码非常混乱,有很多不必要的东西。这是我第一次使用插座,我会清理后,我得到这个工作正常
# 1 楼答案
首先,您正在调用
dis.readFully(mybytearray, 0, mybytearray.length)
,但没有使用该值,因此将丢弃前512个字节接下来,您将在数据之前写入文件名(
writeUTF(...)
)和数组长度(writeLong(...)
),但您只读取文件名(readUTF()
),而不是数组长度,因此数组长度的8个字节将成为数据的前8个字节仅供参考:区块大小相对来说没有意义,因为客户端和服务器不必使用相同的区块大小。所有这些都是套接字中的数据流,套接字实现可以缓冲并将流数据分割成更适合传输协议(可能是以太网)的片段