对于家庭作业:我的任务是编写一个带有确认的 UDP 文件传输程序......基本上模拟 TCP。
我决定分阶段处理这项任务,并且很早就收到了文件问题。我发送一个带有字符“测试文件”的小文本文件,在另一端创建的文件包含匹配的 ascii HEX 值,填充为 0x00。
我希望收到的文件与发送的文件完全相同。
有人可以指出问题吗?
蒂亚
public class UDPRead{
DatagramSocket socket;
String filename, initString;
byte[] buffer;
DatagramPacket initPacket, receivedPacket;
FileOutputStream fileWriter;
int bytesReceived, bytesToReceive;
public UDPRead(int port) throws IOException
{
socket = new DatagramSocket(port);
buffer = new byte[512];
initPacket = receivePacket();
StringTokenizer token = new StringTokenizer(initString, "::");
filename = token.nextToken();
bytesToReceive = new Integer(token.nextToken()).intValue();
//Send reply containing SEND to the sender
send(initPacket.getAddress(), initPacket.getPort(), (new String("SEND")).getBytes());
fileWriter = new FileOutputStream(filename);
while(bytesReceived < bytesToReceive)
{
receivedPacket = receivePacket();
fileWriter.write(receivedPacket.getData(), 0, receivedPacket.getLength());
bytesReceived = bytesReceived + receivedPacket.getLength();
}
}
public DatagramPacket receivePacket() throws IOException{
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
return packet;
}
public byte[] receiveData() throws IOException{
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
return packet.getData();
}
public void send(InetAddress recv, int port,byte[] message)
throws IOException {
DatagramPacket packet = new DatagramPacket(message, message.length, recv, port);
socket.send(packet);
}
}
UDP发送
public UDPSend(InetAddress address, int port) throws IOException{
toPort = port;
toAddress = address;
msg = new byte[512];
buffer = new byte[512];
socket = new DatagramSocket();
socket.connect(toAddress, toPort);
}
@Override
public void sendFile(File theFile) throws IOException{
fileReader = new FileInputStream(theFile);
fileLength = fileReader.available();
send((theFile.getName()+"::"+fileLength).getBytes());
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
socket.receive(reply);
if (new String(reply.getData(), 0, reply.getLength()).equals("OK"))
{
while (currentPos<fileLength){
bytesRead = fileReader.read(msg);
send(msg);
currentPos = currentPos + bytesRead;
}
System.out.println(" -- File transfer complete...");
}
else{System.out.println("Recieved something other than SEND... exiting");}
}
private void send(byte[] message) throws IOException {
DatagramPacket packet = new DatagramPacket(message, message.length);
socket.send(packet);
}
}