Пример #1
0
  public void setNeighbours(Message message) {

    String msg = message.message;
    String[] msg_data = msg.split(" ");
    int neigh_count = Integer.parseInt(msg_data[2]);
    if (neigh_count == 9999 || neigh_count == 9998 || neigh_count == 9997 || neigh_count == 9996) {

      System.out.println("Registration failed..!!!");
    }
    if (neigh_count == 1) {

      Configuration.setNeighbor(msg_data[3], Integer.parseInt(msg_data[4]));
      joinWithNeighbor(msg_data[3], Integer.parseInt(msg_data[4]));

    } else if (neigh_count == 2) {

      Configuration.setNeighbor(msg_data[3], Integer.parseInt(msg_data[4]));
      Configuration.setNeighbor(msg_data[6], Integer.parseInt(msg_data[7]));

      joinWithNeighbor(msg_data[3], Integer.parseInt(msg_data[4]));
      joinWithNeighbor(msg_data[6], Integer.parseInt(msg_data[7]));

    } else if (neigh_count > 2) {

      int rand = (int) Math.floor(Math.random() * neigh_count);

      Configuration.setNeighbor(msg_data[3 * rand + 3], Integer.parseInt(msg_data[3 * rand + 4]));
      int neigh_port_1 = Integer.parseInt(msg_data[3 * rand + 4]), neigh_port_2;
      String neigh_ip_1 = msg_data[3 * rand + 3], neigh_ip_2;

      joinWithNeighbor(neigh_ip_1, neigh_port_1);

      while (true) {
        rand = (int) Math.floor(Math.random() * neigh_count);
        neigh_ip_2 = msg_data[3 * rand + 3];
        neigh_port_2 = Integer.parseInt(msg_data[3 * rand + 4]);

        if (neigh_ip_1.equals(neigh_ip_2) && neigh_port_1 == neigh_port_2) continue;
        else {
          Configuration.setNeighbor(neigh_ip_2, neigh_port_2);
          joinWithNeighbor(neigh_ip_2, neigh_port_2);
          break;
        }
      }
      for (int x = 0; x < neigh_count; x++) {
        Configuration.setBackUpNeighbor(msg_data[3 * x + 3], Integer.parseInt(msg_data[3 * x + 4]));
      }
    }
  }
Пример #2
0
  public void onMessageReceived(Message message) {

    Message newMessage;
    switch (message.msgType) {
      case REGOK:
        setNeighbours(message);
        break;
      case UNROK:
        break;
      case LEAVEOK:
        break;
      case JOINOK:
        break;
      case SER:
        sendSEROKMsg(message);
        break;
      case SEROK:
        showContainedFiles(message);
        break;
      case LEAVE:
        Configuration.removeNeighbor(message.ip_to, message.port_to);
        this.checkForZeroNeighbors();
        break;
      case JOIN:
        Configuration.setNeighbor(message.ip_to, message.port_to);
        break;
    }
  }
Пример #3
0
  public void checkForZeroNeighbors() {

    if (Configuration.getNeighbors().size() == 0) {
      if (Configuration.getBackUpNeighbors().size() > 0) {
        List<Neighbor> neighbors = Configuration.getBackUpNeighbors();
        Configuration.setNeighbor(
            neighbors.get(0).getIpAddress(), neighbors.get(0).getPortNumber());
      } else {
        System.out.println("This node has no connections.");
      }
    }
  }