Exemplo n.º 1
0
  private void updatePredecessor() {
    // Initialise socket and read/write
    try {
      socket = new Socket(neighbours.getPrePreIp(), 4017); // speaking to pre-predecessor
      sender = new PrintWriter(socket.getOutputStream(), true);
      receiver = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    // Ask for his predecessor
    sender.println(protocol.getPredecessorQuery());

    // Listen for his predecessor - assuming that he is alive
    String response = null;
    try {
      response = receiver.readLine();
    } catch (IOException e) {
      e.printStackTrace();
    }

    // If correct reply, update predecessor
    if (response.contains(protocol.getPredecessorResponse())) {
      // Assign pre-predecessor to predecessor
      neighbours.setPreId(neighbours.getPrePreId());
      neighbours.setPreIp(neighbours.getPrePreIp());

      // Assign pre-pre-predecessor to pre-predecessor
      int whiteSpace1 = response.indexOf(" ");
      String usefulResponse = response.substring(whiteSpace1 + 1, response.length());
      int whiteSpace2 = usefulResponse.indexOf(" ");
      neighbours.setPrePreId(usefulResponse.substring(0, whiteSpace2));
      neighbours.setPrePreIp(usefulResponse.substring(whiteSpace2 + 1, usefulResponse.length()));
    }

    // Close socket and read/write
    try {
      receiver.close();
      sender.close();
      socket.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 2
0
 public void run() {
   boolean flag = true;
   while (flag) {
     if (!isAlive(neighbours.getPreIp())) // Predecessor
     updatePredecessor();
     if (!isAlive(neighbours.getPrePreIp())) // PrePredecessor
     updatePrePredecessor();
     if (!isAlive(neighbours.getSucIp())) // Successor
     updateSuccessor();
   }
 }