Example #1
0
  private static void run() {
    Socket link = null; // Step 1.

    try {
      link = new Socket(host, PORT); // Step 1.

      BufferedReader in =
          new BufferedReader(new InputStreamReader(link.getInputStream())); // Step 2.

      PrintWriter out = new PrintWriter(link.getOutputStream(), true); // Step 2.

      // Set up stream for keyboard entry...
      BufferedReader userEntry = new BufferedReader(new InputStreamReader(System.in));

      String message = "";
      String response;
      do {
        System.out.print("Enter message: ");

        message = userEntry.readLine();
        out.println(message); // Step 3.
        System.out.println("");
        do {
          response = in.readLine();
          System.out.println("SERVER> " + response);
        } while (in.ready());
        if (message.equals("QUIT") && response.startsWith("+OK")) {
          link.close();
          System.exit(0);
        }

      } while (!message.equals("***CLOSE***"));
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        System.out.println("\n* Closing connection... *");
        link.close(); // Step 4.
      } catch (IOException e) {
        System.out.println("Unable to disconnect!");
        System.exit(1);
      }
    }
  }
Example #2
0
    public void run() {
      String messageString;
      long lastActivity = System.currentTimeMillis();
      while (keeprunning) {
        try {
          if (in.ready()) {
            messageString = in.readLine();

            if (messageString == null) continue;
            Message m = new Message(messageString);

            if (m.getCommand().matches("\\d+"))
              try {
                int intcommand = Integer.parseInt(m.getCommand());
                if (intcommand == Constants.RPL_ENDOFMOTD) {
                  System.err.println("MOTD SEEN, must be connected.");
                  if (connected) joinChannels();
                  connected = true;
                } else if (intcommand == Constants.ERR_NICKNAMEINUSE) {
                  System.err.println("NICKNAMEINUSE");
                  namecount++;
                  BotStats.getInstance().setBotname(botdefaultname + namecount);
                  new Message("", "NICK", BotStats.getInstance().getBotname(), "").send();
                  new Message(
                          "",
                          "USER",
                          BotStats.getInstance().getBotname()
                              + " nowhere.com "
                              + BotStats.getInstance().getServername(),
                          BotStats.getInstance().getClientName()
                              + " v."
                              + BotStats.getInstance().getVersion())
                      .send();
                  System.err.println("Setting nick to:" + botdefaultname + namecount);
                }
              } catch (NumberFormatException nfe) {
                // we ignore this
                System.err.println("Unknown command:" + m.getCommand());
              }

            if (m.getCommand().equals("PING")) {
              outqueue.add(new Message("", "PONG", "", m.getTrailing()));
              if (debug) System.out.println("PUNG at " + new Date());
            } else if (BotStats.getInstance().containsIgnoreName(m.getSender())) {
              if (debug) System.out.println("Ignored: " + m);
            } else {
              inqueue.add(m); // add to inqueue
              if (debug) System.out.println(m.toString());
              // System.out.println("Inbuffer: prefix: " + m.prefix + " params: " + m.params + "
              // trailing:"
              // + m.trailing + " command:" + m.command + " sender: " + m.sender + "\n    "
              // + "isCTCP:" + m.isCTCP + " isPrivate:" + m.isPrivate + " CTCPCommand:" +
              // m.CTCPCommand
              // + " CTCPMessage:" + m.CTCPMessage);
            }

            lastActivity = System.currentTimeMillis();
          } else {
            if (System.currentTimeMillis() - lastActivity > 400000) {
              System.err.println("400 seconds since last activity! Attempting reconnect");
              in.close();
              oh.disconnect();
              keeprunning = false;
              reconnect();
              return;
            }
            sleep(100);
          }
        } catch (IOException ioe) {
          System.out.println("EOF on connection: " + ioe.getMessage());
        } catch (InterruptedException ie) {
          System.out.println("Interrupted: " + ie.getMessage());
        } catch (Exception e) {
          System.err.println("Unexpected exception in InputHandler :");
          e.printStackTrace();
        }
      }
    }
Example #3
0
  @Override
  public void run() {
    try {
      socketInput =
          new BufferedReader(
              new InputStreamReader(
                  connectionSocket.getInputStream())); // get the inputstream from other peer
      pieceReader =
          connectionSocket
              .getInputStream(); // return an input stream for reading bytes from this socket.
      socketOutput =
          new DataOutputStream(
              connectionSocket.getOutputStream()); // get the outputstream to others
      // return an output stream for writing bytes to this socket.
    } catch (IOException ex) {
      Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
    }

    // TCP handshake
    if (OtherPeerID != -1) {
      try {
        socketOutput.writeBytes(handshakeMsg);
      } catch (IOException ex) {
        Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
      }

      try {
        while (socketInput.ready() == false) {}

      } catch (Exception e) {
      }
      try {
        checkHandShakeMsg = socketInput.readLine() + "";
      } catch (IOException ex) {
        Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
      }
      checkHandShakeHeader = checkHandShakeMsg.substring(0, 18);
      OtherPeerID = Integer.parseInt(checkHandShakeMsg.substring(28, 32));

    } else // ackhandshake
    {

      try {
        while (socketInput.ready() == false) {}

      } catch (Exception e) {
      }

      try {
        checkHandShakeMsg = socketInput.readLine() + "";
      } catch (IOException ex) {
        Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
      }
      checkHandShakeHeader = checkHandShakeMsg.substring(0, 18);
      OtherPeerID = Integer.parseInt(checkHandShakeMsg.substring(28, 32));

      if (checkHandShakeHeader.equals(handshakeheader)) {

        try { // if it is the right neighbour, write log that peer1 is connected from peer2
          peerProcess.logfile.write(LogWriter.logmsg(1, peerProcess.myPeerID, OtherPeerID));
        } catch (IOException ex) {
          Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {

          socketOutput.writeBytes(handshakeMsg);
        } catch (IOException ex) {
          Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }

    // start transferring
    try {
      while (quited == false
          && (peerProcess.Peers.elementAt(peerProcess.myPeerID % 1000 - 1).obtainAll() == false
              || peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).obtainAll() == false)) {

        try {
          socketOutput.writeBytes(peerNotExitMsg);
          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " sent not quit message to peer "
                  + OtherPeerID
                  + ".");
        } catch (Exception e) {
        }
        try {
          while (socketInput.ready() == false) {
            //
          }
        } catch (Exception e) {
        }
        try {
          MsgFromOtherPeer = socketInput.readLine() + "";
        } catch (IOException ex) {
          Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
        }
        // get the corresponding message length, message type and message payload
        RecvdMsg = MsgFromOtherPeer.split("#");
        msgLen = Integer.parseInt(RecvdMsg[0]);
        msgType = Integer.parseInt(RecvdMsg[1]);
        msgPayload = RecvdMsg[2];
        if (msgType == 8) {

          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " received quit message from peer "
                  + OtherPeerID
                  + ".");
          quited = true;
          break;
        } else if (msgType != 9) {
          System.out.println(
              "Received message type " + msgType + ", expecting quit/not quit message.");
        } else {
          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " received not quit message from peer "
                  + OtherPeerID
                  + ".");
        }

        // bitField exchange
        try {
          mybitfield =
              peerProcess.Peers.elementAt(peerProcess.myPeerID % 1000 - 1).obtainBitField();
          haveMsg = mybitfield.length() + "#" + 4 + "#" + mybitfield + "\n";
          socketOutput.writeBytes(haveMsg);
          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " sent bitfield message to peer "
                  + OtherPeerID
                  + ".");
        } catch (Exception e) {
        }
        try {
          while (socketInput.ready() == false) {}

        } catch (Exception e) {
        }
        try {
          MsgFromOtherPeer = socketInput.readLine() + "";
        } catch (IOException ex) {
          Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
        }
        RecvdMsg = MsgFromOtherPeer.split("#");
        msgLen = Integer.parseInt(RecvdMsg[0]);
        msgType = Integer.parseInt(RecvdMsg[1]);
        msgPayload = RecvdMsg[2];
        if (msgType == 4) {

          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " received bitField message from peer "
                  + OtherPeerID
                  + ".");
          peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).setTheBitField(msgPayload);
        } else if (msgType == 8) {

          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " received quit message from peer "
                  + OtherPeerID
                  + ".");
          quited = true;
          break;
        } else {
          System.out.println(" received message type " + msgType + ", expecting bitField message.");
        }

        if (peerProcess.choked[OtherPeerID % 1000 - 1] == false) {
          try {

            socketOutput.writeBytes(unchokedMsg);
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }
          mybitfield =
              peerProcess.Peers.elementAt(peerProcess.myPeerID % 1000 - 1).obtainBitField();
          haveMsg = mybitfield.length() + "#" + 4 + "#" + mybitfield + "\n";
          try {

            socketOutput.writeBytes(haveMsg);
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }

          try {
            while (socketInput.ready() == false) {}

          } catch (Exception e) {
          }
          try {
            MsgFromOtherPeer = socketInput.readLine();
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }
          RecvdMsg = MsgFromOtherPeer.split("#");
          msgLen = Integer.parseInt(RecvdMsg[0]);
          msgType = Integer.parseInt(RecvdMsg[1]);
          msgPayload = RecvdMsg[2];
          if (msgType == 1) {
            try {
              peerProcess.logfile.write(LogWriter.logmsg(3, peerProcess.myPeerID, OtherPeerID));
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
              while (socketInput.ready() == false) {}
            } catch (Exception e) {
            }
            try {
              MsgFromOtherPeer = socketInput.readLine();
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            RecvdMsg = MsgFromOtherPeer.split("#");
            msgLen = Integer.parseInt(RecvdMsg[0]);
            msgType = Integer.parseInt(RecvdMsg[1]);
            msgPayload = RecvdMsg[2];
            if (msgType == 4) {
              peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).setTheBitField(msgPayload);
              interestedPieceID =
                  peerProcess
                      .Peers
                      .elementAt(peerProcess.myPeerID % 1000 - 1)
                      .obtainInterestedPiece(OtherPeerID);
              try {
                if (interestedPieceID != -1)
                  peerProcess.logfile.write(
                      LogWriter.logmsg(5, peerProcess.myPeerID, OtherPeerID, interestedPieceID));
              } catch (IOException ex) {
                Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
              }
              if (interestedPieceID == -1) {
                try {
                  socketOutput.writeBytes(1 + "#" + 3 + "#" + "-1\n");
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }

                try {
                  while (socketInput.ready() == false) {}
                } catch (Exception e) {
                }
                try {
                  MsgFromOtherPeer = socketInput.readLine() + "";
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }
                RecvdMsg = MsgFromOtherPeer.split("#");
                msgLen = Integer.parseInt(RecvdMsg[0]);
                msgType = Integer.parseInt(RecvdMsg[1]);
                msgPayload = RecvdMsg[2];
                if (msgType == 2) {
                  try {
                    peerProcess.logfile.write(
                        LogWriter.logmsg(6, peerProcess.myPeerID, OtherPeerID));
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  byte[] piececontent = peerProcess.obtainPiece(Integer.parseInt(msgPayload));
                  piecemsg = msgPayload + "#" + 7 + "#" + piececontent.length + "\n";
                  try {
                    socketOutput.writeBytes(piecemsg);

                    while (socketInput.ready() == false) {}

                    try {
                      MsgFromOtherPeer = socketInput.readLine();
                    } catch (Exception e) {
                    }
                    RecvdMsg = MsgFromOtherPeer.split("#");
                    msgLen = Integer.parseInt(RecvdMsg[0]);
                    msgType = Integer.parseInt(RecvdMsg[1]);
                    msgPayload = RecvdMsg[2];
                    if (msgType == 10) {

                      socketOutput.write(piececontent);

                      while (socketInput.ready() == false) {}

                      try {
                        MsgFromOtherPeer = socketInput.readLine();
                      } catch (Exception e) {
                      }
                      RecvdMsg = MsgFromOtherPeer.split("#");
                      msgLen = Integer.parseInt(RecvdMsg[0]);
                      msgType = Integer.parseInt(RecvdMsg[1]);
                      msgPayload = RecvdMsg[2];
                      if (msgType != 10) {
                        System.out.println(
                            "received message type "
                                + msgType
                                + ", expecting channel clear message.");
                      }
                      continue;
                    } else {
                      System.out.println(
                          "received message type "
                              + msgType
                              + ", expecting channel clear message.");
                    }
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                } else if (msgType == 3) {
                  try {

                    peerProcess.logfile.write(
                        LogWriter.logmsg(7, peerProcess.myPeerID, OtherPeerID));
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                }
              } else {
                try {
                  socketOutput.writeBytes(1 + "#" + 2 + "#" + interestedPieceID + "\n");
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }

                try {
                  while (socketInput.ready() == false) {}
                } catch (Exception e) {
                }
                try {
                  MsgFromOtherPeer = socketInput.readLine() + "";
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }
                RecvdMsg = MsgFromOtherPeer.split("#");
                msgLen = Integer.parseInt(RecvdMsg[0]);
                msgType = Integer.parseInt(RecvdMsg[1]);
                msgPayload = RecvdMsg[2];
                if (msgType == 2) {
                  byte[] piececontent = peerProcess.obtainPiece(Integer.parseInt(msgPayload));
                  piecemsg = msgPayload + "#" + 7 + "#" + piececontent.length + "\n";
                  try {
                    try {
                      peerProcess.logfile.write(
                          LogWriter.logmsg(6, peerProcess.myPeerID, OtherPeerID));
                    } catch (IOException ex) {
                      Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    socketOutput.writeBytes(piecemsg);

                    while (socketInput.ready() == false) {}
                    try {
                      MsgFromOtherPeer = socketInput.readLine();
                    } catch (Exception e) {
                    }
                    RecvdMsg = MsgFromOtherPeer.split("#");
                    msgLen = Integer.parseInt(RecvdMsg[0]);
                    int indexFromOther = msgLen;
                    msgType = Integer.parseInt(RecvdMsg[1]);
                    msgPayload = RecvdMsg[2];
                    int loadsize = Integer.parseInt(msgPayload);
                    byte[] mspiececon = new byte[loadsize];
                    if (msgType == 7) {
                      if (peerProcess.myPeerID < OtherPeerID) {

                        socketOutput.writeBytes(channelClearMsg);

                        while (pieceReader.available() <= 0) {}

                        int totallen = 0;
                        byte[] c = new byte[1];
                        while (totallen < loadsize) {
                          try {
                            pieceReader.read(c);
                          } catch (Exception e) {
                          }
                          mspiececon[totallen] = c[0];
                          totallen++;
                        }
                        socketOutput.write(piececontent);
                        try {

                          peerProcess.writebackPiece(indexFromOther, mspiececon);
                          peerProcess.logfile.write(
                              LogWriter.logmsg(
                                  8,
                                  peerProcess.myPeerID,
                                  OtherPeerID,
                                  interestedPieceID,
                                  peerProcess
                                      .Peers
                                      .elementAt(peerProcess.myPeerID % 1000 - 1)
                                      .hasHowManyPieces()));

                          if (peerProcess
                                  .Peers
                                  .elementAt(peerProcess.myPeerID % peerIDBase - 1)
                                  .obtainAll()
                              == true) {
                            try {
                              peerProcess.logfile.write(LogWriter.logmsg(9, peerProcess.myPeerID));
                            } catch (Exception e) {
                            }
                          }
                        } catch (IOException ex) {
                          Logger.getLogger(SocketThread.class.getName())
                              .log(Level.SEVERE, null, ex);
                        }

                        while (socketInput.ready() == false) {}

                        try {
                          MsgFromOtherPeer = socketInput.readLine();
                        } catch (Exception e) {
                        }
                        RecvdMsg = MsgFromOtherPeer.split("#");
                        msgLen = Integer.parseInt(RecvdMsg[0]);
                        msgType = Integer.parseInt(RecvdMsg[1]);
                        msgPayload = RecvdMsg[2];
                        if (msgType != 10) {
                          System.out.println(
                              "Expecting channel clear message, received message type " + msgType);
                        }
                        continue;
                      } else {

                        while (socketInput.ready() == false) {}

                        try {
                          MsgFromOtherPeer = socketInput.readLine();
                        } catch (Exception e) {
                        }
                        RecvdMsg = MsgFromOtherPeer.split("#");
                        msgLen = Integer.parseInt(RecvdMsg[0]);
                        msgType = Integer.parseInt(RecvdMsg[1]);
                        msgPayload = RecvdMsg[2];
                        if (msgType == 10) {

                          socketOutput.write(piececontent);

                          while (pieceReader.available() <= 0) {}

                          int totallen = 0;
                          byte[] c = new byte[1];
                          while (totallen < loadsize) {
                            try {
                              pieceReader.read(c);
                            } catch (Exception e) {
                            }
                            mspiececon[totallen] = c[0];
                            totallen++;
                          }
                          socketOutput.writeBytes(channelClearMsg);
                          try {

                            peerProcess.writebackPiece(indexFromOther, mspiececon);
                            peerProcess.logfile.write(
                                LogWriter.logmsg(
                                    8,
                                    peerProcess.myPeerID,
                                    OtherPeerID,
                                    interestedPieceID,
                                    peerProcess
                                        .Peers
                                        .elementAt(peerProcess.myPeerID % 1000 - 1)
                                        .hasHowManyPieces()));

                            if (peerProcess
                                    .Peers
                                    .elementAt(peerProcess.myPeerID % peerIDBase - 1)
                                    .obtainAll()
                                == true) {
                              try {
                                peerProcess.logfile.write(
                                    LogWriter.logmsg(9, peerProcess.myPeerID));
                              } catch (Exception e) {
                              }
                            }
                          } catch (IOException ex) {
                            Logger.getLogger(SocketThread.class.getName())
                                .log(Level.SEVERE, null, ex);
                          }
                          continue;
                        } else {
                          System.out.println(
                              "Expecting channel clear message, received message type " + msgType);
                        }
                      }
                    } else {
                      System.out.println(
                          "Expecting piecemessage, received message type " + msgType);
                    }

                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                } else if (msgType == 3) {
                  try {

                    peerProcess.logfile.write(
                        LogWriter.logmsg(7, peerProcess.myPeerID, OtherPeerID));
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  try {

                    MsgFromOtherPeer = socketInput.readLine() + "";
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  RecvdMsg = MsgFromOtherPeer.split("#");
                  msgLen = Integer.parseInt(RecvdMsg[0]);
                  int indexFromOther = msgLen;
                  msgType = Integer.parseInt(RecvdMsg[1]);
                  msgPayload = RecvdMsg[2];
                  int loadsize = Integer.parseInt(msgPayload);
                  byte[] mspiececon = new byte[loadsize];
                  if (msgType == 7) {
                    socketOutput.writeBytes(channelClearMsg);

                    while (pieceReader.available() <= 0) {}
                    int totallen = 0;
                    byte[] c = new byte[1];
                    while (totallen < loadsize) {
                      try {
                        pieceReader.read(c);
                      } catch (Exception e) {
                      }
                      mspiececon[totallen] = c[0];
                      totallen++;
                    }
                    socketOutput.writeBytes(channelClearMsg);
                    try {

                      peerProcess.writebackPiece(indexFromOther, mspiececon);
                      peerProcess.logfile.write(
                          LogWriter.logmsg(
                              8,
                              peerProcess.myPeerID,
                              OtherPeerID,
                              interestedPieceID,
                              peerProcess
                                  .Peers
                                  .elementAt(peerProcess.myPeerID % 1000 - 1)
                                  .hasHowManyPieces()));

                      if (peerProcess
                              .Peers
                              .elementAt(peerProcess.myPeerID % peerIDBase - 1)
                              .obtainAll()
                          == true) {
                        try {
                          peerProcess.logfile.write(LogWriter.logmsg(9, peerProcess.myPeerID));
                        } catch (Exception e) {
                        }
                      }
                    } catch (IOException ex) {
                      Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    continue;
                  } else {
                    System.out.println(
                        "Expecting piece data, received message type" + msgType + ".");
                  }
                }
              }
            }
          } else if (msgType == 0) {

            try {
              peerProcess.logfile.write(LogWriter.logmsg(4, peerProcess.myPeerID, OtherPeerID));
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }

            try {
              while (socketInput.ready() == false) {}

            } catch (Exception e) {
            }
            try {
              MsgFromOtherPeer = socketInput.readLine();
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            RecvdMsg = MsgFromOtherPeer.split("#");
            msgLen = Integer.parseInt(RecvdMsg[0]);
            msgType = Integer.parseInt(RecvdMsg[1]);
            msgPayload = RecvdMsg[2];
            if (msgType == 2) {
              byte[] piececontent = peerProcess.obtainPiece(Integer.parseInt(msgPayload));
              piecemsg = msgPayload + "#" + 7 + "#" + piececontent.length + "\n";
              try {
                socketOutput.writeBytes(piecemsg);

                while (socketInput.ready() == false) {}

                try {
                  MsgFromOtherPeer = socketInput.readLine();
                } catch (Exception e) {
                }
                RecvdMsg = MsgFromOtherPeer.split("#");
                msgLen = Integer.parseInt(RecvdMsg[0]);
                msgType = Integer.parseInt(RecvdMsg[1]);
                msgPayload = RecvdMsg[2];
                if (msgType == 10) {

                  socketOutput.write(piececontent);

                  while (socketInput.ready() == false) {}

                  try {
                    MsgFromOtherPeer = socketInput.readLine();
                  } catch (Exception e) {
                  }
                  RecvdMsg = MsgFromOtherPeer.split("#");
                  msgLen = Integer.parseInt(RecvdMsg[0]);
                  msgType = Integer.parseInt(RecvdMsg[1]);
                  msgPayload = RecvdMsg[2];
                  if (msgType != 10) {
                    System.out.println(
                        "Expecting channel clear message, received message type " + msgType);
                  }
                  continue;
                } else {
                  System.out.println(
                      "Expecting channel clear message, received message type " + msgType);
                }
              } catch (IOException ex) {
                Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
              }
              try {
                peerProcess.logfile.write(LogWriter.logmsg(6, peerProcess.myPeerID, OtherPeerID));
              } catch (IOException ex) {
                Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
              }
            } else if (msgType == 3) {
              try {

                peerProcess.logfile.write(LogWriter.logmsg(7, peerProcess.myPeerID, OtherPeerID));
              } catch (IOException ex) {
                Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
              }
            }
          } else {
            continue;
          }
        } else {
          try {
            socketOutput.writeBytes(chokedMsg);
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }

          try {
            while (socketInput.ready() == false) {}

          } catch (Exception e) {
          }
          try {
            MsgFromOtherPeer = socketInput.readLine() + "";
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }
          RecvdMsg = MsgFromOtherPeer.split("#");
          msgLen = Integer.parseInt(RecvdMsg[0]);
          msgType = Integer.parseInt(RecvdMsg[1]);
          msgPayload = RecvdMsg[2];
          if (msgType == 0) {

            try {
              peerProcess.logfile.write(LogWriter.logmsg(4, peerProcess.myPeerID, OtherPeerID));
            } catch (Exception e) {
            }

            continue;
          } else if (msgType == 1) {

            try {
              peerProcess.logfile.write(LogWriter.logmsg(3, peerProcess.myPeerID, OtherPeerID));
            } catch (Exception e) {
            }
            try {
              while (socketInput.ready() == false) {}

            } catch (Exception e) {
            }
            try {
              MsgFromOtherPeer = socketInput.readLine() + "";
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            RecvdMsg = MsgFromOtherPeer.split("#");
            msgLen = Integer.parseInt(RecvdMsg[0]);
            msgType = Integer.parseInt(RecvdMsg[1]);
            msgPayload = RecvdMsg[2];
            if (msgType == 4) {

              peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).setTheBitField(msgPayload);
              interestedPieceID =
                  peerProcess
                      .Peers
                      .elementAt(peerProcess.myPeerID % 1000 - 1)
                      .obtainInterestedPiece(OtherPeerID);
              try {

                if (interestedPieceID != -1)
                  peerProcess.logfile.write(
                      LogWriter.logmsg(5, peerProcess.myPeerID, OtherPeerID, interestedPieceID));
              } catch (Exception e) {
              }
              if (interestedPieceID == -1) {
                try {
                  socketOutput.writeBytes(1 + "#" + 3 + "#" + "-1\n");
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }
              } else {
                try {
                  socketOutput.writeBytes(1 + "#" + 2 + "#" + interestedPieceID + "\n");
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }

                try {
                  while (socketInput.ready() == false) {}

                } catch (Exception e) {
                }
                try {
                  MsgFromOtherPeer = socketInput.readLine() + "";
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }
                RecvdMsg = MsgFromOtherPeer.split("#");
                msgLen = Integer.parseInt(RecvdMsg[0]);
                int indexFromOther = msgLen;
                msgType = Integer.parseInt(RecvdMsg[1]);
                msgPayload = RecvdMsg[2];
                int loadsize = Integer.parseInt(msgPayload);
                byte[] mspiececon = new byte[loadsize];
                if (msgType == 7) {
                  socketOutput.writeBytes(channelClearMsg);

                  while (pieceReader.available() <= 0) {}
                  int totallen = 0;
                  byte[] c = new byte[1];
                  while (totallen < loadsize) {
                    try {
                      pieceReader.read(c);
                    } catch (Exception e) {
                    }
                    mspiececon[totallen] = c[0];
                    totallen++;
                  }
                  socketOutput.writeBytes(channelClearMsg);
                  try {

                    peerProcess.writebackPiece(indexFromOther, mspiececon);
                    peerProcess.logfile.write(
                        LogWriter.logmsg(
                            8,
                            peerProcess.myPeerID,
                            OtherPeerID,
                            interestedPieceID,
                            peerProcess
                                .Peers
                                .elementAt(peerProcess.myPeerID % 1000 - 1)
                                .hasHowManyPieces()));

                    if (peerProcess
                            .Peers
                            .elementAt(peerProcess.myPeerID % peerIDBase - 1)
                            .obtainAll()
                        == true) {
                      try {
                        peerProcess.logfile.write(LogWriter.logmsg(9, peerProcess.myPeerID));
                      } catch (Exception e) {
                      }
                    }
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  continue;
                } else {
                  System.out.println("received msg type " + msgType + ", expecting piece data.");
                }
              }

            } else {
              System.out.println("received msg type " + msgType + ", expecting have msg.");
            }
          } else {
            System.out.println("received msg type " + msgType + ", expecting choke/unchoke msg.");
          }
        }
      }
    } catch (Exception ite) {
    }

    if (quited == false) {

      try {
        socketOutput.writeBytes(peerExitMsg);
        System.out.println(
            "Peer " + peerProcess.myPeerID + " sent quit message to peer " + OtherPeerID + ".");
        try {
          Thread.sleep(100);
        } catch (Exception e) {
        }
      } catch (IOException ex) {
        Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
      }
    }

    System.out.println(
        "The socket between peer"
            + peerProcess.myPeerID
            + "and peer "
            + OtherPeerID
            + " will disconnect now.\n");
    peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).setHasAllPieces();
    peerProcess.Peers.elementAt(peerProcess.myPeerID % 1000 - 1).setHasAllPieces();
  }
Example #4
0
  // The main procedure
  public static void main(String args[]) {
    String s;

    initGUI();

    while (true) {
      try { // Poll every ~10 ms
        Thread.sleep(10);
      } catch (InterruptedException e) {
      }

      switch (connectionStatus) {
        case BEGIN_CONNECT:
          try {
            // Try to set up a server if host
            if (isHost) {
              hostServer = new ServerSocket(port);
              socket = hostServer.accept();
            }

            // If guest, try to connect to the server
            else {
              socket = new Socket(hostIP, port);
            }

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            changeStatusTS(CONNECTED, true);
          }
          // If error, clean up and output an error message
          catch (IOException e) {
            cleanUp();
            changeStatusTS(DISCONNECTED, false);
          }
          break;

        case CONNECTED:
          try {
            // Send data
            if (toSend.length() != 0) {
              out.print(toSend);
              out.flush();
              toSend.setLength(0);
              changeStatusTS(NULL, true);
            }

            // Receive data
            if (in.ready()) {
              s = in.readLine();
              if ((s != null) && (s.length() != 0)) {
                // Check if it is the end of a trasmission
                if (s.equals(END_CHAT_SESSION)) {
                  changeStatusTS(DISCONNECTING, true);
                }

                // Otherwise, receive what text
                else {
                  appendToChatBox("INCOMING: " + s + "\n");
                  changeStatusTS(NULL, true);
                }
              }
            }
          } catch (IOException e) {
            cleanUp();
            changeStatusTS(DISCONNECTED, false);
          }
          break;

        case DISCONNECTING:
          // Tell other chatter to disconnect as well
          out.print(END_CHAT_SESSION);
          out.flush();

          // Clean up (close all streams/sockets)
          cleanUp();
          changeStatusTS(DISCONNECTED, true);
          break;

        default:
          break; // do nothing
      }
    }
  }
Example #5
0
  /**
   * Read position and size of the login box from a given abstract path.
   *
   * @param abstractPath The path to the file.
   */
  public void readPersistence(String abstractPath) {
    String filepath = FileUtil.openPath(abstractPath);

    if (filepath != null) {
      BufferedReader in;
      String line;
      try {
        File file = new File(filepath);
        in = new BufferedReader(new FileReader(file));
        // File must start with 'Login Panel'
        if ((line = in.readLine()) != null) {
          if (!line.startsWith("Login Panel")) {
            Messages.postWarning("The " + filepath + " file is " + "corrupted and being removed");
            // Remove the corrupted file.
            file.delete();
            // Set the size and position to the full vnmrj frame
            setDefaultSizePosition();

            return;
          }
        }
        String h = null, w = null, x = null, y = null;
        int xi, yi;

        if (in.ready()) h = in.readLine().trim();

        if (in.ready()) w = in.readLine().trim();

        if (in.ready()) x = in.readLine().trim();

        if (in.ready()) y = in.readLine().trim();

        in.close();

        // Save width and height for later use also
        height = Integer.decode(h).intValue();
        width = Integer.decode(w).intValue();
        xi = Integer.decode(x).intValue();
        yi = Integer.decode(y).intValue();
        // Save point for later use also
        position = new Point(xi, yi);

        // Set them
        setSize(width, height);
        setLocation(position);

        // If we got what we need and set the size and position,
        // just return now.
        return;
      }
      // If an exception, continue below
      catch (Exception e) {
      }
    }

    // No file or an excpetion happened, set default size and position
    // Be sure the file is gone
    try {
      if (filepath != null) {
        File file = new File(filepath);
        if (file != null) file.delete();
      }
    }
    // If an exception, just continue below
    catch (Exception e) {
    }

    // Set the size and position to the full vnmrj frame
    setDefaultSizePosition();
  }