Пример #1
0
 public ChatServerThread(Socket socket, ChatServer ChatServer, int id) {
   // super("ChatServerThread");
   this.socket = socket;
   // this.server = ChatServer;
   this.clientID = id;
   p.nl("Connection from: " + socket.toString());
 }
Пример #2
0
 public void leave() {
   try {
     // int id = ChatServer.getClientID(name);
     // ChatServer.sendAll(CS + "e" + name + " has left the ChatServer");
     ChatServer.sendOne(clientID, "kick");
     ChatServer.removeClient(clientID);
     ChatServer.updateUsers();
     socket.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  /** listen: start to listen if there is any clients connected */
  public void listen() {

    // Firstly spawn a new thread and then the main thread
    // also start listening
    _userNet = new DropboxFileServerUserNet(_server, _userOut, _userIn, _userSock);
    _userNet.start();

    /* Use main thread, cannot be stopped */
    while (_sock != null && !_sock.isClosed()) {
      try {
        String line = NetComm.receive(_in);
        _dlog(line);
        parse(line);
      } catch (Exception e) {
        if (!_server.noException()) {
          _elog(e.toString());
        }
        break;
        // Break the loop
      }
    }

    /* Clear */
    // Close main thread
    clear();
    // Cancel the listening thread and retry
    _server.cancelListeningThread();
    /* Also cancel all of the syncers */
    _server.cancelSyncers();
    // Retry after
    try {

      _log(
          "The connection to master is broken,"
              + " reset everything and retry connection after "
              + DropboxConstants.TRY_CONNECT_MILLIS
              + " milliseconds");

      Thread.sleep(DropboxConstants.TRY_CONNECT_MILLIS);

    } catch (InterruptedException e) {
      if (!_server.noException()) {
        _elog(e.toString());
      }
      if (_server.debugMode()) {
        e.printStackTrace();
      }
    }
    _server.run();

    clear();
    _log(_threadName + " is stopped");
  }
Пример #4
0
  public void run() {

    try {
      msgOut = new PrintWriter(socket.getOutputStream(), true);
      msgIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (Exception e) {
      e.printStackTrace();
    }
    try {
      String input;
      String output;

      TextTransferProtocol ttp = new TextTransferProtocol(this); // set up ttp parsey thing
      String first = msgIn.readLine();

      if (first.startsWith(ChatServer.REQ)) {
        if (first.indexOf("/message") > -1) {
          isPing = true;
          msgOut.println(ChatServer.getMotd());
          // ChatServer.pushToChat("ping");
        } else if (first.indexOf("/login") > -1) {
          // ChatServer.pushToChat("login");
          if (name == null) {
            name = first.substring(8, first.length());
            // ChatServer.pushToChat("setting name to " + name);
            // msgOut.println("setting name to " + name);
            if (ChatServer.users.contains(name)) {
              ChatServer.pushToChat(
                  Colors.RED
                      + "User "
                      + name
                      + " already exists, changing to "
                      + name
                      + "_"
                      + ChatServer.users.size()
                      + 1);
              name = name + "_" + ChatServer.users.size();
            }
            ChatServer.addUser(name);
            ChatServer.restoreClientRank(name);
            ChatServer.updateUsers();
          }

          ChatServer.sendAll(Colors.YELLOW + name + " has joined the server");
          ChatServer.sendOne(clientID, ChatServer.getLoginMessage());
          while ((input = msgIn.readLine()) != null) { // continue doing that until ends]
            // ChatServer.pushToChat(input);
            output = ttp.processIn(input);
            if (output != null)
              ChatServer.sendAll(getRankColor() + name + Colors.WHITE + ": " + output);
          }
        }
      } else {
        msgOut.println("400: PLEASE START ANY CONNECTION WITH " + ChatServer.REQ + "/fn");
      }
      socket.close();
      // ChatServer.pushToChat("closed socket");

    } catch (Exception e) {
      e.printStackTrace(msgOut);
      if (!isPing) {
        leave();
        p.nl("Lost connection to user: "******"[WARNING]" + Colors.WHITE + " Lost connection to user: "******"got pinged by: " + socket);
        ChatServer.pushToChat(Colors.YELLOW + "[INFO]" + Colors.WHITE + " Pinged by: " + socket);
      }
      // ChatServer.updateUsers();
      // ChatServer.removeClient(ChatServer.getClientID(name)); //figure out what to do if the
      // client exits without doing /logout
    }
  }
  /**
   * close: close the socket and stream
   *
   * @return: true for success, false for error
   */
  protected boolean close() {
    _dlog("Do main thread closing...");
    if (_sock != null && !_sock.isClosed()) {
      _dlog("Closing the receiving thread");
      try {
        _sock.close();
        _in.close();
        _out.close();

        _sock = null;
        _in = null;
        _out = null;
        _dlog("Success!");
      } catch (IOException e) {
        if (!_server.noException()) {
          _elog(e.toString());
        }
        if (_server.debugMode()) {
          e.printStackTrace();
        }
        return false;
      }
    }
    _sock = null;
    _in = null;
    _out = null;

    _dlog("Cancel the user input thread");
    if (_userNet != null) {
      _userNet.stop();
      _userNet.join(); // guaranteed to be closed
      _userNet = null;
    }
    if (_userSock != null && !_userSock.isClosed()) {
      _dlog("Closing the user input thread");
      // Stop the user thread
      try {
        _userSock.close();
        _userIn.close();
        _userOut.close();
        _userSock = null;
        _userIn = null;
        _userOut = null;
        _dlog("Success!");
      } catch (IOException e) {
        if (!_server.noException()) {
          _elog(e.toString());
        }
        if (_server.debugMode()) {
          e.printStackTrace();
        }
        return false;
      }
    }
    _userSock = null;
    _userIn = null;
    _userOut = null;

    /* Cancel all client nodes */

    _dlog("Finished");
    return true;

    /* CAUTION: _server is never cleared */
  }
  /**
   * connect: connect to the master
   *
   * @return: true for success and false for failure
   */
  protected boolean connect() {

    boolean connected = true;
    try {
      _sock = new Socket(_serverIP, _serverPort);
      _out = new PrintWriter(_sock.getOutputStream(), true);
      _in = new BufferedReader(new InputStreamReader(_sock.getInputStream()));
      String reply = sendAll();
      if (!reply.equals(ProtocolConstants.PACK_STR_CONFIRM_HEAD)) {
        /* Tokenize */
        StringTokenizer st = new StringTokenizer(reply);
        if (st.nextToken().equals(ProtocolConstants.PACK_STR_ERRMES_HEAD)) {
          _elog(st.nextToken());
          return false;
        }
      }

      _userSock = new Socket(_serverIP, _serverPort);
      _userOut = new PrintWriter(_userSock.getOutputStream(), true);
      _userIn = new BufferedReader(new InputStreamReader(_userSock.getInputStream()));
      String replyUser = sendUserID();
      if (!replyUser.equals(ProtocolConstants.PACK_STR_CONFIRM_HEAD)) {
        throw new Exception("Not confirmed");
      }
    } catch (UnknownHostException e) {
      if (!_server.noException()) {
        _elog(e.toString());
      }
      if (_server.debugMode()) {
        e.printStackTrace();
      }
      connected = false;
    } catch (IOException e) {
      if (!_server.noException()) {
        _elog(e.toString());
      }
      if (_server.debugMode()) {
        e.printStackTrace();
      }
      connected = false;
    } catch (Exception e) {
      if (!_server.noException()) {
        _elog(e.toString());
      }
      if (_server.debugMode()) {
        e.printStackTrace();
      }
      connected = false;
    }
    if (!connected) {
      return connected;
    }

    if (!connected) {
      /* Remove the pair of socket */
      _sock = null;
      _in = null;
      _out = null;

      _userSock = null;
      _userOut = null;
      _userIn = null;
    }
    return connected;
  }