udp停止等待ack不工作

时间:2012-03-14 23:36:53

标签: java udp

我正在尝试实现UDP Stop-and-Wait协议。我设法让我的UDP发送器和接收器成功传输图像文件。现在我正在尝试实现ACK。

当我的发送者完成发送数据包时,它等待接收者发送ACK。一旦接收方从发送方接收到数据包,接收方就会发送ACK。 以下是发送方中等待ACK的代码: 其中seqNum是发送方刚刚发送给接收方的包号,sendPacket是刚刚发送的包。我将此作为参数添加,以防发件人需要重新发送。

private static void receiveACK(int seqNum, DatagramPacket sendPacket) throws IOException {
        byte[] ack = new byte[2];
        boolean received = false;
        int recSeqNum = -1;
        ByteArrayInputStream bais = new ByteArrayInputStream(ack);
        DataInputStream dis = new DataInputStream(bais);
        DatagramPacket receivePacket = new DatagramPacket(ack, ack.length);
        while(!received) {
            try {
                clientSocket.setSoTimeout(50);
                clientSocket.receive(receivePacket);
                recSeqNum = dis.readShort();
                System.out.println("ACK: " + ack );
            } catch (SocketTimeoutException e) {
                System.out.println("Timed out: Still waiting for ACK");
            }
            System.out.println(recSeqNum);
            if(recSeqNum == seqNum) {
                received = true;
            } else {
                clientSocket.send(sendPacket);
            }
        }
    }

以下是接收方中发送ACK的代码:

private static void sendACK(int seqNum, InetAddress returnAddress) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeShort(seqNum);
        dos.flush();
        System.out.println("send: " + seqNum);
        byte[] sendArray = baos.toByteArray();
        DatagramPacket sendPacket = new DatagramPacket(sendArray, sendArray.length, returnAddress, port );
        receieverSocket.send(sendPacket);
    }

问题是接收器只是不断尝试发送第一个数据包而发送者只是超时。

发件人和收件人都在同一台机器上。

0 个答案:

没有答案