RDT项目实施校验和,确认

时间:2018-11-22 01:20:54

标签: java checksum transfer

我需要使用校验和,ACK,序列号和倒数计时器来实现可靠的数据传输,并实现以下功能。

  public static int compute_checksum(String message) {}

  public static boolean isCorrupt(rdtPacket packet) {}

  public static boolean isACK(rdtPacket packet) {}

  public static boolean inOrder(rdtPacket packet, int seqno) {} // has_seq()

并在等待ACK时向套接字添加一个倒数计时器。

此外,数据包格式为:

消息校验和序列号

最后,将使用消息“ ACK”发送ACK

这是我到目前为止所拥有的:

import java.io.*;
import java.net.*;

class RDTClient {
  private static DatagramSocket clientSocket;
  private static InetAddress IPAddress;
  private static final int serverPort = 9876;

  public static void main(String args[]) throws Exception {
    try {
      String serverHostname = new String("127.0.0.1");

      if (args.length > 0) {
        serverHostname = args[0];
      }

      BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

      clientSocket = new DatagramSocket();

      IPAddress = InetAddress.getByName(serverHostname);
      System.out.println("Attemping to connect to " + IPAddress + ") via UDP port " + serverPort);

      System.out.print("Enter Message: ");
      String message = inFromUser.readLine();

      rdt_send(message);

      // String response = rdt_rcv();
      // System.out.println("Received response: " + response);

      clientSocket.close();
    } catch (UnknownHostException ex) {
      System.err.println(ex);
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }

  private static String make_pkt(String message) {
    System.out.println("[RDTClient:make_pkt] " + message);
    return message;
  }

  private static void rdt_send(String message) {
    System.out.println("[RDTClient:rdt_send] " + message);
    String packet = make_pkt(message);
    udt_send(packet);
  }

  private static void udt_send(String message) {
    // compute the message checksum and create the segment rdt_send and make_pkt
    try {
      byte[] sendData = new byte[1024];
      sendData = message.getBytes();
      DatagramPacket sendPacket =
      new DatagramPacket(sendData, sendData.length, IPAddress, serverPort);
      clientSocket.send(sendPacket);
      System.out.println("[RDTClient:udt_send] Message sent");
    } catch (IOException ioe) {
      System.out.println("Failed to send");
    }
  }

  private static String rdt_rcv() {
    try {
      byte[] receiveData = new byte[1024];
      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
      clientSocket.setSoTimeout(10000);
      clientSocket.receive(receivePacket);
      String message = new String(receivePacket.getData());
      IPAddress = receivePacket.getAddress();
      int port = receivePacket.getPort();

      System.out.println("[RDTClient:rdt_rcv] Received packet from: " + IPAddress + ":" + port);
      return message;
    } catch (IOException ioe) {
      System.out.println("Failed to read from port");
    }
    return "";
  }
}

0 个答案:

没有答案