我正在研究将接收数据的算法,我想将它们写入文件。 我收到的第一个数据包是包含fileName的数据包。 第二个数据包包含sizeOfPacket。 然后我必须计算收到的数据包数量。 但是,当我想接收下一个数据包并将这些数据包逐字节写入文件时,我的实际问题就开始了。 我尝试了很多方法,但是每次生成的文件只有1kb大,而实际图像是72kb大。 我必须从第4个字节读取数据包,因为前4个字节将数据包的位置存储在文件中。
每个数据包的大小为1024B
public void run(int port) throws IOException {
try {
byte[] receiveData = new byte[1024];
DatagramSocket serverSocket = new DatagramSocket(port);
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(
receiveData,
SIZE_OF_PACKET
);
//first packet with name of file
serverSocket.receive(receivePacket);
String fileName = utils.getFileName(receivePacket);
//System.out.println(fileName);
//System.out.println(fileName.length());
//second packet with size of whole data()
serverSocket.receive(receivePacket);
int sizeOfFile = utils.BytesToInt(receivePacket);
//get number of packets that are needed
int numOfPackets = utils.getNumOfPackets(sizeOfFile);
//System.out.println(sizeOfFile);
//System.out.println(numOfPackets);
//output stream for file "test.jpg"
FileOutputStream fos = new FileOutputStream("test.jpg");
//loop over for the number of Packets
for(int i = 0; i < numOfPackets - 1; i++) {
serverSocket.receive(receivePacket);
receiveData = receivePacket.getData();
//byte byte after byte and write it to the file
// start at index 3 bcs first byte is packet number
for(int a = 3; a < SIZE_OF_PACKET - 1;a++) {
Byte nextByte = receiveData[a];
if(nextByte != 0) fos.write(nextByte);
}
}
fos.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}