Пример #1
0
 public void run() {
   try {
     OutputStream out = new BufferedOutputStream(socket.getOutputStream());
     while (!socket.isClosed()) {
       out.write(data);
     }
   } catch (IOException ex) {
     if (!socket.isClosed()) {
       try {
         socket.close();
       } catch (IOException e) {
         // Oh well. We tried
       }
     }
   }
 }
 /**
  * there is an issue with this method: if it is called often enough, the <CODE>
  * _s.sendUrgentData(0);</CODE> method that it invokes, will force the <CODE>_s</CODE> socket to
  * close on the other end, at least on Windows systems. This behavior is due to the fact that
  * OOB data handling is problematic since there are conflicting specifications in TCP.
  * Therefore, it is required that the method is not called with high frequency (see the <CODE>
  * PDBTExecSingleCltWrkInitSrv._CHECK_PERIOD_MSECS</CODE> flag in this file.)
  *
  * @return true iff the worker is available to accept work according to all evidence.
  */
 private synchronized boolean getAvailability() {
   boolean res = _isAvail && _s != null && _s.isClosed() == false;
   if (res && _OK2SendOOB) { // work-around the OOB data issue
     // last test using OOB sending of data
     try {
       _OK2SendOOB = false; // indicates should not send OOB data until set to true
       _s.sendUrgentData(0); // unfortunately, if this method is called often enough,
       // it will cause the socket to close???
       res = true;
     } catch (IOException e) {
       // e.printStackTrace();
       utils.Messenger.getInstance()
           .msg("PDBTExecSingleCltWrkInitSrv.getAvailability(): Socket has been closed", 0);
       res = false;
       _isAvail = false; // declare availability to false as well
       // try graceful exit
       try {
         _s.shutdownOutput();
         _s.close(); // Now we can close the Socket
       } catch (IOException e2) {
         // silently ignore
       }
     }
   }
   return res;
 }
 @Override
 public boolean isOpen() {
   return (mIn != null
       && mOut != null
       && mSocket != null
       && mSocket.isConnected()
       && !mSocket.isClosed());
 }
Пример #4
0
 public void sendMessage(ObjectExchange data) throws IOException {
   synchronized (this) {
     if (writer != null && !socket.isClosed()) {
       //  data.friend_id  =   transactionId;
       writer.writeObject(data);
       writer.flush();
     }
   }
 }
Пример #5
0
    private void doConnect(InetSocketAddress addr) throws IOException {
      dest = new Socket();
      try {
        dest.connect(addr, 10000);
      } catch (SocketTimeoutException ex) {
        sendError(HOST_UNREACHABLE);
        return;
      } catch (ConnectException cex) {
        sendError(CONN_REFUSED);
        return;
      }
      // Success
      InetAddress iadd = addr.getAddress();
      if (iadd instanceof Inet4Address) {
        out.write(PROTO_VERS);
        out.write(REQUEST_OK);
        out.write(0);
        out.write(IPV4);
        out.write(iadd.getAddress());
      } else if (iadd instanceof Inet6Address) {
        out.write(PROTO_VERS);
        out.write(REQUEST_OK);
        out.write(0);
        out.write(IPV6);
        out.write(iadd.getAddress());
      } else {
        sendError(GENERAL_FAILURE);
        return;
      }
      out.write((addr.getPort() >> 8) & 0xff);
      out.write((addr.getPort() >> 0) & 0xff);
      out.flush();

      InputStream in2 = dest.getInputStream();
      OutputStream out2 = dest.getOutputStream();

      Tunnel tunnel = new Tunnel(in2, out);
      tunnel.start();

      int b = 0;
      do {
        // Note that the socket might be closed from another thread (the tunnel)
        try {
          b = in.read();
          if (b == -1) {
            in.close();
            out2.close();
            return;
          }
          out2.write(b);
        } catch (IOException ioe) {
        }
      } while (!client.isClosed());
    }
Пример #6
0
 public void close() throws IOException {
   if (in != null) {
     in.close();
   }
   if (out != null) {
     out.close();
   }
   if (socket != null && !socket.isClosed()) {
     socket.close();
   }
 }
  /** 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");
  }
Пример #8
0
  // メッセージ監視用のスレッド
  public void run() {
    try {
      InputStream input = socket.getInputStream();
      BufferedReader reader = new BufferedReader(new InputStreamReader(input));
      while (!socket.isClosed()) {
        String line = reader.readLine();

        String[] msg = line.split(" ", 2);
        String msgName = msg[0];
        String msgValue = (msg.length < 2 ? "" : msg[1]);

        reachedMessage(msgName, msgValue);
      }
    } catch (Exception err) {
    }
  }
Пример #9
0
 public void closedSession() {
   try {
     if ((socket == null) || socket.isClosed()) {
       return;
     }
     sendMessage(
         new ObjectExchangeWrap(OUT_SESSION_CLOSE, null, transactionId).getObjectExchange());
     writer.close();
     reader.close();
     socket.close();
     this.interrupt();
     System.out.println("Showdown input and output");
   } catch (Exception e) {
     System.out.println("try shutdown error");
     System.out.println(e.getMessage());
   }
 }
    public void sendMessage(Address address, byte[] message) throws java.io.IOException {
      Socket s = null;
      SocketEntry entry = (SocketEntry) sockets.get(address);
      if (logger.isDebugEnabled()) {
        logger.debug("Looking up connection for destination '" + address + "' returned: " + entry);
        logger.debug(sockets.toString());
      }
      if (entry != null) {
        s = entry.getSocket();
      }
      if ((s == null) || (s.isClosed())) {
        if (logger.isDebugEnabled()) {
          logger.debug("Socket for address '" + address + "' is closed, opening it...");
        }
        SocketChannel sc = null;
        try {
          // Open the channel, set it to non-blocking, initiate connect
          sc = SocketChannel.open();
          sc.configureBlocking(false);
          sc.connect(
              new InetSocketAddress(
                  ((TcpAddress) address).getInetAddress(), ((TcpAddress) address).getPort()));
          s = sc.socket();
          entry = new SocketEntry((TcpAddress) address, s);
          entry.addMessage(message);
          sockets.put(address, entry);

          synchronized (pending) {
            pending.add(entry);
          }

          selector.wakeup();
          logger.debug("Trying to connect to " + address);
        } catch (IOException iox) {
          logger.error(iox);
          throw iox;
        }
      } else {
        entry.addMessage(message);
        synchronized (pending) {
          pending.add(entry);
        }
        selector.wakeup();
      }
    }
Пример #11
0
    private void doBind(InetSocketAddress addr) throws IOException {
      ServerSocket svr = new ServerSocket();
      svr.bind(null);
      InetSocketAddress bad = (InetSocketAddress) svr.getLocalSocketAddress();
      out.write(PROTO_VERS);
      out.write(REQUEST_OK);
      out.write(0);
      out.write(IPV4);
      out.write(bad.getAddress().getAddress());
      out.write((bad.getPort() >> 8) & 0xff);
      out.write((bad.getPort() & 0xff));
      out.flush();
      dest = svr.accept();
      bad = (InetSocketAddress) dest.getRemoteSocketAddress();
      out.write(PROTO_VERS);
      out.write(REQUEST_OK);
      out.write(0);
      out.write(IPV4);
      out.write(bad.getAddress().getAddress());
      out.write((bad.getPort() >> 8) & 0xff);
      out.write((bad.getPort() & 0xff));
      out.flush();
      InputStream in2 = dest.getInputStream();
      OutputStream out2 = dest.getOutputStream();

      Tunnel tunnel = new Tunnel(in2, out);
      tunnel.start();

      int b = 0;
      do {
        // Note that the socket might be close from another thread (the tunnel)
        try {
          b = in.read();
          if (b == -1) {
            in.close();
            out2.close();
            return;
          }
          out2.write(b);
        } catch (IOException ioe) {
        }
      } while (!client.isClosed());
    }
Пример #12
0
 public void run() {
   try {
     prepareClient();
     logger.info("Starting normal session with " + getClientName());
     while (true) {
       this.receive();
     }
   } catch (IOException ioe) {
     logger.warn("Client " + this + " has been disconnected.");
     this.setDisabled(true);
     users.remove(this);
   } finally {
     try {
       if (s != null && !s.isClosed()) {
         s.close();
         logger.warn("Socket with " + this + " has been closed.");
       }
     } catch (IOException ioe) {
       logger.error("Socket has not been closed.", ioe);
     }
   }
 }
Пример #13
0
 public boolean isConnected() {
   return !sock.isClosed() && sock.isConnected();
 }
Пример #14
0
 public boolean ok() {
   // Use this to test whether a client is stil
   // valid for use.
   return !socket.isClosed() && socket.isConnected() && socket.isBound();
 }
  /**
   * 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 */
  }
Пример #16
0
  /*
   *    Gathers the fields necessary to construct an email message using MIME format. Also gathers the user's credentials
   *
   */
  void getUserInput() {
    // Buffered writer for reading input from user
    String authentication;
    String retryTemp;
    boolean retry = false;
    boolean showOptions = true;
    boolean authFlag = false;
    boolean hasResponded = false;

    try {
      do {
        writer = new BufferedReader(new InputStreamReader(System.in));
        String replyCode;

        // ***********Getting username and password********************
        System.out.print("Username: "******"Password: "******" " + writer.readLine();
        System.out.println();

        // Sending Authentication data to server
        System.out.println("AUTH " + authentication);
        out.println("AUTH " + authentication);
        do {
          replyCode = in.readLine();
          if (replyCode != null) {
            hasResponded = true;
            // System.out.println(replyCode);
            if (replyCode.substring(0, 3).equals("777")) {
              authFlag = true;
              System.out.println("Authentication successful!");
            }
          }
        } while (hasResponded == false);

        if (authFlag == false) // If authentication failed, exit or retry
        {
          System.out.println("Authentication error! Exit(e) or Retry(r)?");
          retryTemp = writer.readLine();
          if (retryTemp.equals("r")) retry = true;
          else if (retryTemp.equals("e")) {
            retry = false;
            System.exit(0);
          }
        } else // Authentication worked!
        {
          int choice;
          do {
            System.out.println("****************OPTIONS*****************");
            System.out.println(
                "Press (1) to send an email\n"
                    + "Press (2) to retrieve messages\n"
                    + "Press (3) to exit.\n"
                    + "***************************************");
            choice = Integer.parseInt(writer.readLine());
            switch (choice) {
              case 1: // Gather user input for email structure
                System.out.print("To: ");
                receiver_email_address = writer.readLine();

                System.out.print("From: ");
                sender_email_address = writer.readLine();

                System.out.print("Subject: ");
                subject = writer.readLine();

                System.out.println("Message Body");
                message_body = writer.readLine();

                MIME =
                    ("From: "
                        + sender_email_address
                        + "\n"
                        + "To: "
                        + receiver_email_address
                        + "\n"
                        + "Subject: "
                        + subject
                        + "\n"
                        + "MIME-version: 1.0\n"
                        + "Content-Transfer-Encoding: 7bit\n"
                        + "Content-Type: text/plain\r\n\n"
                        + message_body);
                state = SMTP_State.HELO;
                System.out.println(
                    "Socket Status: \nisConnected? : "
                        + socket.isConnected()
                        + "\nisClosed?: "
                        + socket.isClosed());

                out.println("SEND");
                System.out.println("SEND, ENTERING SERVER COMMUNICATION PHASE");
                sendToServer();
                break;

              case 2:
                out.println("PRNT: " + "markramasco");
                popConnection();
                break;

              case 3:
                showOptions = false;
                break;
            }

          } while (showOptions);
          socket.close();
        }

        // ***************Getting email**********************

      } while (retry);

    } catch (IOException e) {
      System.out.println(e);
    }
  }
Пример #17
0
 public boolean isOpen() {
   return sock != null && !sock.isClosed();
 }
Пример #18
0
    private void getRequestV4() throws IOException {
      int ver = in.read();
      int cmd = in.read();
      if (ver == -1 || cmd == -1) {
        // EOF
        in.close();
        out.close();
        return;
      }

      if (ver != 0 && ver != 4) {
        out.write(PROTO_VERS4);
        out.write(91); // Bad Request
        out.write(0);
        out.write(0);
        out.write(0);
        out.write(0);
        out.write(0);
        out.write(0);
        out.write(0);
        out.flush();
        purge();
        out.close();
        in.close();
        return;
      }

      if (cmd == CONNECT) {
        int port = ((in.read() & 0xff) << 8);
        port += (in.read() & 0xff);
        byte[] buf = new byte[4];
        readBuf(in, buf);
        InetAddress addr = InetAddress.getByAddress(buf);
        // We don't use the username...
        int c;
        do {
          c = (in.read() & 0xff);
        } while (c != 0);
        boolean ok = true;
        try {
          dest = new Socket(addr, port);
        } catch (IOException e) {
          ok = false;
        }
        if (!ok) {
          out.write(PROTO_VERS4);
          out.write(91);
          out.write(0);
          out.write(0);
          out.write(buf);
          out.flush();
          purge();
          out.close();
          in.close();
          return;
        }
        out.write(PROTO_VERS4);
        out.write(90); // Success
        out.write((port >> 8) & 0xff);
        out.write(port & 0xff);
        out.write(buf);
        out.flush();
        InputStream in2 = dest.getInputStream();
        OutputStream out2 = dest.getOutputStream();

        Tunnel tunnel = new Tunnel(in2, out);
        tunnel.start();

        int b = 0;
        do {
          try {
            b = in.read();
            if (b == -1) {
              in.close();
              out2.close();
              return;
            }
            out2.write(b);
          } catch (IOException ex) {
          }
        } while (!client.isClosed());
      }
    }
 private boolean isConnectionLost() {
   return _s == null || _s.isClosed();
 }
Пример #20
0
 public boolean isClosed() {
   return socket.isClosed();
 }