Ejemplo n.º 1
1
  public static void main(String[] args) throws IOException, InterruptedException {
    boolean running = true;
    // udp protocol over a socket.
    DatagramSocket socket = new DatagramSocket();

    while (running) {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      String line = br.readLine();
      String[] inputs = line.split(" ");

      if (inputs.length < 2) {
        System.out.println("Usage: username command id");
        socket.close();
        return;
      }

      byte[] byteArr = (inputs[0] + " " + inputs[1] + " " + inputs[2]).getBytes();

      // send request
      byte[] buf = new byte[256];
      InetAddress address = InetAddress.getByName("localhost");
      DatagramPacket packet = new DatagramPacket(byteArr, byteArr.length, address, 4445);
      socket.send(packet);

      // get response
      packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);

      // display response
      String received = new String(packet.getData(), 0, packet.getLength());
      System.out.println("From server: " + received);
    }
    //   socket.close();
  }
Ejemplo n.º 2
0
  public static void main(final String... args) throws Throwable {
    final String remotehost = args[0];
    final int remoteport = Integer.parseInt(args[1]);
    final DatagramSocket socket = new DatagramSocket();

    final byte buffer[] = new byte[512];

    final InetSocketAddress remote = new InetSocketAddress(remotehost, remoteport);

    buffer[0] = ENQUIRY;
    buffer[1] = END_OF_TRANSMISSION;
    socket.send(new DatagramPacket(buffer, 2, remote));

    final DatagramPacket p = new DatagramPacket(buffer, buffer.length);
    socket.receive(p);

    if ((p.getLength() == 2) && (buffer[0] == ACKNOWLEDGE) && (buffer[1] == END_OF_TRANSMISSION))
      System.out.println("Connection established");
    else {
      System.out.println("Connection failed");
      return;
    }

    for (; ; ) {
      int ptr = 0;
      for (int d; (d = System.in.read()) != '\n'; ) buffer[ptr++] = (byte) d;

      socket.send(new DatagramPacket(buffer, ptr, remote));
    }
  }
Ejemplo n.º 3
0
  void setBufferSizes() {
    if (sock != null) {
      try {
        sock.setSendBufferSize(ucast_send_buf_size);
      } catch (Throwable ex) {
        Trace.warn("UDP.setBufferSizes()", "failed setting ucast_send_buf_size in sock: " + ex);
      }
      try {
        sock.setReceiveBufferSize(ucast_recv_buf_size);
      } catch (Throwable ex) {
        Trace.warn("UDP.setBufferSizes()", "failed setting ucast_recv_buf_size in sock: " + ex);
      }
    }

    if (mcast_sock != null) {
      try {
        mcast_sock.setSendBufferSize(mcast_send_buf_size);
      } catch (Throwable ex) {
        Trace.warn(
            "UDP.setBufferSizes()", "failed setting mcast_send_buf_size in mcast_sock: " + ex);
      }

      try {
        mcast_sock.setReceiveBufferSize(mcast_recv_buf_size);
      } catch (Throwable ex) {
        Trace.warn(
            "UDP.setBufferSizes()", "failed setting mcast_recv_buf_size in mcast_sock: " + ex);
      }
    }
  }
Ejemplo n.º 4
0
  public static void main(String[] args) {
    int port = 5555;

    DatagramSocket socket;
    socket = null;
    try {
      socket = new DatagramSocket(port);
      socket.setBroadcast(true);
      socket.connect(InetAddress.getByName("255.255.255.255"), 5555);
    } catch (Exception e) {
      System.err.println("Connection failed. " + e.getMessage());
    }

    while (true) {
      String message = "hey";
      byte[] buf = message.getBytes();

      DatagramPacket packet = new DatagramPacket(buf, buf.length);
      try {
        socket.send(packet);
      } catch (Exception e) {
        System.err.println("Sending failed. " + e.getMessage());
      }
    }
  }
  public static void main(String args[]) {
    DatagramSocket skt = null;
    try {
      skt = new DatagramSocket(6789);
      byte[] buffer = new byte[1000];
      while (true) {
        DatagramPacket request = new DatagramPacket(buffer, buffer.length);
        skt.receive(request);
        System.out.println("Data received from client");
        System.out.println(new String(request.getData()));
        Thread.sleep(15000);

        String[] arrayMsg = (new String(request.getData())).split(" ");

        System.out.println(arrayMsg[0] + "server processed");

        byte[] sendMsg = (arrayMsg[0] + "server processed").getBytes();

        DatagramPacket reply =
            new DatagramPacket(sendMsg, sendMsg.length, request.getAddress(), request.getPort());

        System.out.println("sending data from server to client");
        Thread.sleep(15000);
        ;
        skt.send(reply);
      }
    } catch (Exception e) {

    }
  }
  /**
   * Tries to obtain a mapped/public address for the specified port (possibly by executing a STUN
   * query).
   *
   * @param dst the destination that we'd like to use this address with.
   * @param port the port whose mapping we are interested in.
   * @return a public address corresponding to the specified port or null if all attempts to
   *     retrieve such an address have failed.
   * @throws IOException if an error occurs while stun4j is using sockets.
   * @throws BindException if the port is already in use.
   */
  public InetSocketAddress getPublicAddressFor(InetAddress dst, int port)
      throws IOException, BindException {
    if (!useStun || (dst instanceof Inet6Address)) {
      logger.debug(
          "Stun is disabled for destination "
              + dst
              + ", skipping mapped address recovery (useStun="
              + useStun
              + ", IPv6@="
              + (dst instanceof Inet6Address)
              + ").");
      // we'll still try to bind though so that we could notify the caller
      // if the port has been taken already.
      DatagramSocket bindTestSocket = new DatagramSocket(port);
      bindTestSocket.close();

      // if we're here then the port was free.
      return new InetSocketAddress(getLocalHost(dst), port);
    }
    StunAddress mappedAddress = queryStunServer(port);
    InetSocketAddress result = null;
    if (mappedAddress != null) result = mappedAddress.getSocketAddress();
    else {
      // Apparently STUN failed. Let's try to temporarily disble it
      // and use algorithms in getLocalHost(). ... We should probably
      // eveng think about completely disabling stun, and not only
      // temporarily.
      // Bug report - John J. Barton - IBM
      InetAddress localHost = getLocalHost(dst);
      result = new InetSocketAddress(localHost, port);
    }
    if (logger.isDebugEnabled())
      logger.debug("Returning mapping for port:" + port + " as follows: " + result);
    return result;
  }
Ejemplo n.º 7
0
  public static void main(String args[]) throws Exception {
    // Making a text file
    String filename =
        "C:\\Users\\S.S. Mehta\\Desktop\\Codes\\ComputerNetworks\\CN_project\\CN_project\\test3.txt";
    makeTextFile(filename);

    // Reading the file and puttin it in buffer
    BufferedReader in = new BufferedReader(new FileReader(filename));
    char[] c1 = new char[PACKET_SIZE];
    c1 = readData(in);
    displayPacket(c1);

    // Step3 - making a socket , makeing a packet with inet address and sending it
    byte[] buffer = new byte[PACKET_SIZE];
    DatagramSocket skt = new DatagramSocket(PORT_NUMBER);
    DatagramPacket request = new DatagramPacket(buffer, buffer.length);

    // stop till you receive
    wait(skt, request);
    System.out.println("On server side \nrequest received from Slient");
    // making a packet with an inet address -
    InetAddress host = InetAddress.getByName("localhost");

    DatagramPacket reply = makePacket(c1, host);

    // Sending reply packet
    System.out.println("Sending reply packet to client");
    Thread.sleep(5000);
    skt.send(reply);

    // closing the socket
    skt.close();
  }
Ejemplo n.º 8
0
 static String printSocket(DatagramSocket socket) {
   return "[Socket: localPort="
       + socket.getLocalPort()
       + ", remoteAddr="
       + socket.getInetAddress()
       + ", localAddr="
       + socket.getLocalAddress()
       + "]";
 }
Ejemplo n.º 9
0
  void closeSocket() {
    if (sock != null) {
      // by sending a dummy packet, the thread will terminate (if it was flagged as stopped before)
      sendDummyPacket(sock.getLocalAddress(), sock.getLocalPort());

      sock.close();
      sock = null;
      if (Trace.trace) {
        Trace.info("UDP.closeSocket()", "socket closed");
      }
    }
  }
Ejemplo n.º 10
0
  /** Generic constructor for the name service interface */
  public LeetActive(String svc_host, int svc_port, int portNum) {

    try {
      nameServer = new DatagramSocket();
      nameServer.setSoTimeout(3000);
      nameServer.connect(InetAddress.getByName(svc_host), svc_port);
    } catch (Exception e) {
      System.err.println("LA " + e);
    }
    this.portNum = portNum;
    hostList = new ArrayList();
  }
Ejemplo n.º 11
0
  public void run() {
    while (listen) {
      try {
        byte[] buf = new byte[256];
        byte[] buf2 = new byte[256];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        InetAddress address;
        socket.receive(packet);
        String in = new String(packet.getData(), 0, packet.getLength());
        address = packet.getAddress();
        int port = packet.getPort();
        // newClient = findPort(port, address, newClient);
        String name = findPerson(port, address);
        // System.out.println(name);
        if (in.startsWith("1")) {
          String nama = new String(packet.getData(), 0, packet.getLength());
          nama = nama.substring(1);
          newClient = new Client(packet.getAddress(), packet.getPort(), nama);
          threads.add(newClient);
          String wel =
              "\nWelcome "
                  + newClient.nama
                  + "\n "
                  + "to quit type \"bye\" and to whisper use prefix @name : ";
          buf = (wel).getBytes();
          packet = new DatagramPacket(buf, buf.length, packet.getAddress(), packet.getPort());
          socket.send(packet);
          wel = " enters the room";
          buf = (newClient.nama + wel).getBytes();
          Broadcast(address, port, buf);
        } else if (in.startsWith("@")) {
          // findPort(port, address, newClient);
          Whisper(newClient, packet.getData());
        } else if (in.equals("bye")) {

          String bye = name + " is leaving";
          buf2 = bye.getBytes();
          // packet = new DatagramPacket(buf,buf.length,newClient.address, newClient.port);
          Broadcast(address, port, buf2);

        } else {
          byte[] buf3 = new byte[256];
          String text =
              name + "<broadcast> : " + new String(packet.getData(), 0, packet.getLength());
          buf3 = text.getBytes();
          Broadcast(packet.getAddress(), packet.getPort(), buf3);
        }
      } catch (IOException ex) {
        Logger.getLogger(DatagramServer.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    socket.close();
  }
Ejemplo n.º 12
0
  /**
   * Schedule a timer for retransmission.
   *
   * @throws Exception if message cannot be sent on the socket
   */
  public void schedule() throws Exception {
    sock.send(message);

    /* choose a random between [-1, 1] */
    int rand = new Random().nextInt(2) - 1;
    timer.schedule(new RetransmissionHandler(), (interval + rand) * 1000);
  }
Ejemplo n.º 13
0
  private void listen() throws Exception {
    System.out.println("Listening on port: " + serverPort);
    // Initialize socket
    socket = new DatagramSocket(serverPort);

    // While running
    while (run) {

      // Wait for handshake
      packet = new DatagramPacket(response, response.length);
      socket.receive(packet); // Blocking
      // System.out.println("RT: got packet");
      Packet p = new Packet(packet.getData());

      if (p.isHandshake()) {
        // System.out.println("RT: is handshake");
        // Get client connection info
        InetAddress IPAddress = packet.getAddress();
        int port = packet.getPort();

        // Process handshake
        processHandshake(p, IPAddress, port);

        // Get message
        MyMessage message = getMessage();

        if (message != null) {
          rc.rreceive(message);
        }
      }
    }
  }
Ejemplo n.º 14
0
  public static void Whisper(Client newClient, byte[] buf) {
    String input = new String(buf, 0, buf.length);
    input = input.substring(1);
    byte[] sendbuff = new byte[256];
    String[] parts = null;
    String text = null;
    String whisperTo = null;

    try {
      parts = input.split(" : ");
      whisperTo = parts[0]; // 004
      // System.out.println(newClient.nama+" "+whisperTo);
      text = parts[1];
    } catch (ArrayIndexOutOfBoundsException e) {
      String notif = "wrong prefix";
      sendbuff = notif.getBytes();
      DatagramPacket packet =
          new DatagramPacket(sendbuff, sendbuff.length, newClient.address, newClient.port);
    }
    String prefix = newClient.nama + " : " + text;
    sendbuff = prefix.getBytes();

    for (Client h : threads) {
      if (h.nama.equals(whisperTo)) {
        DatagramPacket packet = new DatagramPacket(sendbuff, sendbuff.length, h.address, h.port);
        try {
          socket.send(packet);
        } catch (IOException ex) {
          Logger.getLogger(DatagramServer.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }
  }
Ejemplo n.º 15
0
 public static void wait(DatagramSocket skt, DatagramPacket request)
     throws IOException, InterruptedException {
   // stop till you receive
   skt.receive(request);
   System.out.println("request received");
   Thread.sleep(2000);
 }
    protected void destroy() {
      search_destroyed = true;

      if (twc != null) {

        twc.destroy();

        twc = null;
      }

      if (timer_event != null) {

        timer_event.cancel();

        timer_event = null;
      }

      if (control_socket != null) {

        try {
          control_socket.close();

        } catch (Throwable e) {
        }

        control_socket = null;
      }
    }
Ejemplo n.º 17
0
  public void destory() {
    procMsgThd.stop0();
    procMsgThd.interrupt();
    mainThread.interrupt();
    if (group != null) {
      try {
        if (recvSocket instanceof MulticastSocket) {
          ((MulticastSocket) recvSocket).leaveGroup(group);
        }
      } catch (IOException ioe) {
      }
    }

    sendSocket.close();
    recvSocket.close();
  }
Ejemplo n.º 18
0
 void doSend(byte[] data, InetAddress dest, int port) throws IOException {
   DatagramPacket packet;
   packet = new DatagramPacket(data, data.length, dest, port);
   if (sock != null) {
     sock.send(packet);
   }
 }
Ejemplo n.º 19
0
  /**
   * Workaround for the problem encountered in certains JDKs that a thread listening on a socket
   * cannot be interrupted. Therefore we just send a dummy datagram packet so that the thread 'wakes
   * up' and realizes it has to terminate. Should be removed when all JDKs support
   * Thread.interrupt() on reads. Uses sock t send dummy packet, so this socket has to be still
   * alive.
   *
   * @param dest The destination host. Will be local host if null
   * @param port The destination port
   */
  void sendDummyPacket(InetAddress dest, int port) {
    DatagramPacket packet;
    byte[] buf = {0};

    if (dest == null) {
      try {
        dest = InetAddress.getLocalHost();
      } catch (Exception e) {
      }
    }

    if (Trace.debug) {
      Trace.info("UDP.sendDummyPacket()", "sending packet to " + dest + ":" + port);
    }
    if (sock == null || dest == null) {
      Trace.warn(
          "UDP.sendDummyPacket()", "sock was null or dest was null, cannot send dummy packet");
      return;
    }
    packet = new DatagramPacket(buf, buf.length, dest, port);
    try {
      sock.send(packet);
    } catch (Throwable e) {
      Trace.error(
          "UDP.sendDummyPacket()",
          "exception sending dummy packet to " + dest + ":" + port + ": " + e);
    }
  }
 /**
  * The method queries a Stun server for a binding for the port and address that <tt>sock</tt> is
  * bound on.
  *
  * @param sock the socket whose port and address we'dlike to resolve (the stun message gets sent
  *     trhough that socket)
  * @return StunAddress the address returned by the stun server or null if an error occurred or no
  *     address was returned
  * @throws IOException if an error occurs while stun4j is using sockets.
  * @throws BindException if the port is already in use.
  */
 private StunAddress queryStunServer(DatagramSocket sock) throws IOException, BindException {
   StunAddress mappedAddress = null;
   if (detector != null && useStun) {
     mappedAddress = detector.getMappingFor(sock);
     if (logger.isTraceEnabled()) {
       logger.trace(
           "For socket with address "
               + sock.getLocalAddress().getHostAddress()
               + " and port "
               + sock.getLocalPort()
               + " the stun server returned the "
               + "following mapping ["
               + mappedAddress
               + "]");
     }
   }
   return mappedAddress;
 }
  /**
   * Returns an InetAddress instance that represents the localhost, and that a socket can bind upon
   * or distribute to peers as a contact address.
   *
   * @param intendedDestination the destination that we'd like to use the localhost address with.
   * @return an InetAddress instance representing the local host, and that a socket can bind upon or
   *     distribute to peers as a contact address.
   */
  public synchronized InetAddress getLocalHost(InetAddress intendedDestination) {
    // no point in making sure that the localHostFinderSocket is initialized.
    // better let it through a NullPointerException.
    InetAddress localHost = null;
    localHostFinderSocket.connect(intendedDestination, this.RANDOM_ADDR_DISC_PORT);
    localHost = localHostFinderSocket.getLocalAddress();
    localHostFinderSocket.disconnect();
    // windows socket implementations return the any address so we need to
    // find something else here ... InetAddress.getLocalHost seems to work
    // better on windows so lets hope it'll do the trick.
    if (localHost.isAnyLocalAddress()) {
      try {
        // all that's inside the if is an ugly IPv6 hack
        // (good ol' IPv6 - always causing more problems than it solves.)
        if (intendedDestination instanceof Inet6Address) {
          // return the first globally routable ipv6 address we find
          // on the machine (and hope it's a good one)
          Enumeration interfaces = NetworkInterface.getNetworkInterfaces();

          while (interfaces.hasMoreElements()) {
            NetworkInterface iface = (NetworkInterface) interfaces.nextElement();
            Enumeration addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
              InetAddress address = (InetAddress) addresses.nextElement();
              if (address instanceof Inet6Address) {
                if (!address.isAnyLocalAddress()
                    && !address.isLinkLocalAddress()
                    && !address.isSiteLocalAddress()
                    && !address.isLoopbackAddress()) {
                  return address;
                }
              }
            }
          }
        } else localHost = InetAddress.getLocalHost();
        /** @todo test on windows for ipv6 cases */
      } catch (Exception ex) {
        // sigh ... ok return 0.0.0.0
        logger.warn("Failed to get localhost ", ex);
      }
    }

    return localHost;
  }
Ejemplo n.º 22
0
    public void run() {
      try {
        byte[] in_data = new byte[pkt_size];
        DatagramPacket in_pkt = new DatagramPacket(in_data, in_data.length);
        try {
          while (true) {
            sk_in.receive(in_pkt);
            System.out.print(
                (new Date().getTime())
                    + ": sender received "
                    + in_pkt.getLength()
                    + "bytes from "
                    + in_pkt.getAddress().toString()
                    + ":"
                    + in_pkt.getPort()
                    + ". data are ");
            for (int i = 0; i < pkt_size; ++i) System.out.print(in_data[i]);
            System.out.println();
            try {
              String res = new String(in_data);
              String[] arr = new String[2];
              arr = res.split(" ");
              System.out.println(arr[0]);
              System.out.println(arr[1]);
              if ((arr[0].trim().equalsIgnoreCase(String.valueOf(curr)))
                  && (arr[1].trim().equalsIgnoreCase("ACK")
                      && (arr[2].trim().equalsIgnoreCase(String.valueOf(617709412))))) {
                curr++;
              }
            } catch (Exception e) {

            }
          }

        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          sk_in.close();
        }
      } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
      }
    }
Ejemplo n.º 23
0
 public static void main(String[] args) throws Exception {
   if (args.length == 1) {
     DatagramSocket serverSocket; // The server Socket.
     int rec_port = Integer.parseInt(args[0]); // The port on which the server is listening.
     serverSocket = new DatagramSocket(rec_port);
     while (true) {
       echo("\n");
       echo("Listening on port: " + rec_port);
       byte[] receivedData =
           new byte[1]; // The buffer byte array where the received data is stored.
       DatagramPacket clientRequest =
           new DatagramPacket(receivedData, receivedData.length); // Server Packet.
       serverSocket.receive(clientRequest); // Server listening on specified port.
       Server_Receive cli_Thread = new Server_Receive(serverSocket, clientRequest, receivedData);
       cli_Thread.start(); // Server_Receive thread started.
     }
   } else {
     echo("Enter only port. See README");
   }
 }
Ejemplo n.º 24
0
  String dumpSocketInfo() throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.append("local_addr=").append(local_addr);
    sb.append(", mcast_addr=").append(mcast_addr);
    sb.append(", bind_addr=").append(bind_addr);
    sb.append(", ttl=").append(ip_ttl);

    if (sock != null) {
      sb.append("\nsocket: bound to ");
      sb.append(sock.getLocalAddress().getHostAddress()).append(":").append(sock.getLocalPort());
      sb.append(", receive buffer size=").append(sock.getReceiveBufferSize());
      sb.append(", send buffer size=").append(sock.getSendBufferSize());
    }

    if (mcast_sock != null) {
      sb.append("\nmulticast socket: bound to ");
      sb.append(mcast_sock.getInterface().getHostAddress())
          .append(":")
          .append(mcast_sock.getLocalPort());
      sb.append(", send buffer size=").append(mcast_sock.getSendBufferSize());
      sb.append(", receive buffer size=").append(mcast_sock.getReceiveBufferSize());
    }
    return sb.toString();
  }
Ejemplo n.º 25
0
 void handleDiagnosticProbe(InetAddress sender, int port) {
   try {
     byte[] diag_rsp = getDiagResponse().getBytes();
     DatagramPacket rsp = new DatagramPacket(diag_rsp, 0, diag_rsp.length, sender, port);
     if (Trace.trace) {
       Trace.info(
           "UDP.handleDiagnosticProbe()", "sending diag response to " + sender + ":" + port);
     }
     sock.send(rsp);
   } catch (Throwable t) {
     Trace.error(
         "UDP.handleDiagnosticProbe()",
         "failed sending diag rsp to " + sender + ":" + port + ", exception=" + t);
   }
 }
    protected void sendBeacon() {
      if (is_enabled) {

        try {
          byte[] bytes = encodeBeacon(true, tcp_port);

          control_socket.send(
              new DatagramPacket(
                  bytes, bytes.length, InetAddress.getByName("255.255.255.255"), CONTROL_PORT));

        } catch (Throwable e) {

          log("Failed to send beacon", e);
        }
      }
    }
Ejemplo n.º 27
0
 public static void Broadcast(InetAddress address, int port, byte[] buf) {
   // System.out.println(port + " " + findPerson(port,address) );
   for (Client h : threads) {
     // System.out.println(h.port + " "+h.nama);
     // System.out.println(threads.size());
     if (h.port != port) {
       // && !address.equals(h.address)
       DatagramPacket packet = new DatagramPacket(buf, buf.length, h.address, h.port);
       try {
         socket.send(packet);
         // System.out.println("yang di broadcast " +h.port + " "+h.nama);
         // System.out.println(new String(packet.getData(),0,packet.getLength()));
       } catch (IOException ex) {
         Logger.getLogger(DatagramServer.class.getName()).log(Level.SEVERE, null, ex);
       }
     }
   }
 }
Ejemplo n.º 28
0
  private boolean sendAck(Packet p, DatagramPacket dp) {

    // Respond
    // System.out.println("RT: Sending ack for packet w/ seqnum: " + p.getSeqNum());
    Packet hsp = new Packet(p.getSeqNum());
    hsp.assembleHandshakePacket();
    packet =
        new DatagramPacket(hsp.getPacketData(), hsp.getPacketSize(), dp.getAddress(), dp.getPort());

    try {
      socket.send(packet);
    } catch (Exception e) {
      System.out.println("RT: Could not send ack packet:\n" + e.getMessage());
      return false;
    }

    return true;
  }
Ejemplo n.º 29
0
  private int processHandshake(Packet p, InetAddress ip, int port) throws Exception {
    // System.out.println("Got handshake");
    // Get connection information
    this.numMessages = p.getNumMessages();
    this.totalDataSize = p.getTotalDataLength();
    this.seqNum = p.getSeqNum();

    // Respond
    // System.out.println("RT: Sending handshake response");
    Packet hsp = new Packet(seqNum);
    hsp.assembleHandshakePacket();
    packet = new DatagramPacket(hsp.getPacketData(), hsp.getPacketSize(), ip, port);
    socket.send(packet);

    // System.out.println("RT: Done with handshake:\n\tStarting seqnum: "+seqNum+"\n\tTotal datalen:
    // "+totalDataSize);
    return 1; // FIXME p.getNumMessages();
  }
Ejemplo n.º 30
0
  private MyMessage getMessage() throws Exception {
    int dataRecieved = 0;
    String m = new String();
    String t;

    // FIXME needs to get multiple packets and messages
    // System.out.println("RT: Now waiting for message data");

    while (dataRecieved < totalDataSize) {
      // Get message data
      response = new byte[65000];
      DatagramPacket packet = new DatagramPacket(response, response.length);
      socket.receive(packet);
      Packet p = new Packet(packet.getData());
      // System.out.println("RT: Got message with seqnum: "+p.getSeqNum());

      // If we have a handshake packet something broke
      if (p.isHandshake()) {
        return null;
      }

      // If next in-order packet grab data and is not corrupt
      // XXX
      if (p.getSeqNum() == seqNum + 1 && p.checkChecksum()) {
        // Get the message ( part? )
        // System.out.println("RT: Is correct seqnum");
        t = p.getMessages().get(0).getMessageContents();
        // System.out.println("RT: Got message packet: " + t);
        m += t;

        // Send ack
        sendAck(p, packet);

        // Increment counters
        dataRecieved += t.length();
        seqNum++;
      } else {
        System.out.println("RT: Is NOT correct seqnum");
      }
    }
    MyMessage result = new MyMessage();
    result.setMessageContents(m);
    return result;
  }