示例#1
0
 @Override
 public void run() {
   while (commandLineSocket.isConnected()) {
     String output = keyboardScanner.nextLine();
     commandLinePrintWriter.println(output);
   }
 }
示例#2
0
  public static void main(String[] args) throws IOException {
    int queueLenth = 10; // number of clients that can connect at the same time
    int clientPort = 4500; // port that JokeClient and JokeServer communicate on
    Socket socketClient;

    // initialize joke and proverb databases
    Database joke = new JokeDatabase();
    Database proverb = new ProverbDatabase();

    System.out.println("Christian Loera's Joke server, listening at port 4500 and 4891.\n");

    ServerAdmin servAdmin = new ServerAdmin(); // initialize ServerAdmin class
    Thread threadAdmin = new Thread(servAdmin); // create new thread of ServerAdmin class
    threadAdmin
        .start(); // start ServerAdmin thread to handle JokeClientAdmin connection asynchronously

    @SuppressWarnings("resource")
    ServerSocket clientServerSocket =
        new ServerSocket(
            clientPort, queueLenth); // creates socket that binds at port JokeClient connects to

    System.out.println("Client server is running");
    while (true) {
      socketClient = clientServerSocket.accept(); // listening for JokeClient
      if (socketClient
          .isConnected()) // if socketClient connects to JokeClient execute new thread of Worker
      new Worker(socketClient, joke, proverb, mode).start();
    }
  }
 @Override
 public boolean isOpen() {
   return (mIn != null
       && mOut != null
       && mSocket != null
       && mSocket.isConnected()
       && !mSocket.isClosed());
 }
示例#4
0
 @Override
 public void run() {
   while (commandLineSocket.isConnected()) {
     String input = commandLineInputScanner.nextLine();
     localPrintWriter.println(input);
     if (input.equals("Copying...")) {
       readFile();
     }
   }
 }
示例#5
0
    public void run() {
      try {
        while (((fromClientObject = in.readObject()) != null) && connection.isConnected()) {

          if (fromClientObject.getClass() == String.class) {
            synchronized (players) {
              String playerName = (String) fromClientObject;
              players.addPlayer(ID, playerName, 0);
              broadcast(players);
            }
          }

          if (fromClientObject.getClass() == Integer.class) {
            synchronized (players) {
              int tableSize = (int) fromClientObject;
              players.changeTableSize(ID, tableSize);
              broadcast(players);
            }
          }

          if (fromClientObject.getClass() == ClickEvent.class) {
            ClickEvent click = (ClickEvent) fromClientObject;
            ctrl.receiveClick(click);
          }

          checkToGameStart();
        }
      } catch (Exception e) {
        ctrl.serverError("Client disconnected!");
      } finally {
        try {
          System.out.println(ID);
          synchronized (receiverList) {
            Collection<ReceiverThread> found =
                Collections.synchronizedList(new ArrayList<ReceiverThread>());
            for (ReceiverThread actualReceiver : receiverList) {
              if (actualReceiver.getID() == ID) {
                found.add(actualReceiver);
              }
            }
            receiverList.removeAll(found);
          }
          synchronized (players) {
            players.removePlayer(ID);
          }
          broadcast(players);
          connection.close();
        } catch (IOException e) {
          ctrl.serverError("Error while closing connection!");
        }
      }
    }
 /*
  * Write a String to the Client output stream
  */
 private boolean writeMsg(String msg) {
   // if Client is still connected send the message to it
   if (!socket.isConnected()) {
     close();
     return false;
   }
   // write the message to the stream
   try {
     sOutput.writeObject(msg);
   }
   // if an error occurs, do not abort just inform the user
   catch (IOException e) {
     display("Error sending message to " + username);
     display(e.toString());
   }
   return true;
 }
示例#7
0
  public void checkConn() {
    try {

      if (!socket.isConnected()) {
        for (int i = 1; i <= Server.ConnectionArray.size(); i++) {
          if (Server.ConnectionArray.get(i) == socket) {
            Server.ConnectionArray.remove(i);
          }
        }
        for (int i = 1; i <= Server.ConnectionArray.size(); i++) {
          Socket tSocket = (Socket) Server.ConnectionArray.get(i - 1);
          PrintWriter tOut = new PrintWriter(tSocket.getOutputStream());
          tOut.println(tSocket.getLocalAddress().getHostName() + " disconnected!");
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
示例#8
0
文件: Server.java 项目: naory159/Ex4
 /*
  * Write a String to the Client output stream
  */
 private boolean writeMsg(ChatMessage cm) {
   // if Client is still connected send the message to it
   if (!socket.isConnected()) {
     close();
     return false;
   }
   // write the message to the stream
   try {
     boolean sendChatMessage = cm.getType() == ChatMessage.ESTABLISHCONNECTION;
     boolean sendMediaFileMessage = cm.getType() == ChatMessage.ESTABLISHCONNECTIONANDPLAY;
     if (sendChatMessage || sendMediaFileMessage) sOutput.writeObject(cm);
     else sOutput.writeObject(cm.getMessage());
   }
   // if an error occurs, do not abort just inform the user
   catch (IOException e) {
     display("Error sending message to " + username);
     display(e.toString());
   }
   return true;
 }
示例#9
0
 public boolean isConnected() {
   return !sock.isClosed() && sock.isConnected();
 }
示例#10
0
 public boolean ok() {
   // Use this to test whether a client is stil
   // valid for use.
   return !socket.isClosed() && socket.isConnected() && socket.isBound();
 }
示例#11
0
  /** Internal method. Get and check response packet from searchd. */
  private byte[] _GetResponse(Socket sock) {
    /* connect */
    DataInputStream sIn = null;
    InputStream SockInput = null;
    try {
      SockInput = sock.getInputStream();
      sIn = new DataInputStream(SockInput);

    } catch (IOException e) {
      _error = "getInputStream() failed: " + e;
      return null;
    }

    /* read response */
    byte[] response = null;
    short status = 0, ver = 0;
    int len = 0;
    try {
      /* read status fields */
      status = sIn.readShort();
      ver = sIn.readShort();
      len = sIn.readInt();

      /* read response if non-empty */
      if (len <= 0) {
        _error = "invalid response packet size (len=" + len + ")";
        return null;
      }

      response = new byte[len];
      sIn.readFully(response, 0, len);

      /* check status */
      if (status == SEARCHD_WARNING) {
        DataInputStream in = new DataInputStream(new ByteArrayInputStream(response));

        int iWarnLen = in.readInt();
        _warning = new String(response, 4, iWarnLen);

        System.arraycopy(response, 4 + iWarnLen, response, 0, response.length - 4 - iWarnLen);

      } else if (status == SEARCHD_ERROR) {
        _error = "searchd error: " + new String(response, 4, response.length - 4);
        return null;

      } else if (status == SEARCHD_RETRY) {
        _error = "temporary searchd error: " + new String(response, 4, response.length - 4);
        return null;

      } else if (status != SEARCHD_OK) {
        _error = "searched returned unknown status, code=" + status;
        return null;
      }

    } catch (IOException e) {
      if (len != 0) {
        /* get trace, to provide even more failure details */
        PrintWriter ew = new PrintWriter(new StringWriter());
        e.printStackTrace(ew);
        ew.flush();
        ew.close();
        String sTrace = ew.toString();

        /* build error message */
        _error =
            "failed to read searchd response (status="
                + status
                + ", ver="
                + ver
                + ", len="
                + len
                + ", trace="
                + sTrace
                + ")";
      } else {
        _error = "received zero-sized searchd response (searchd crashed?): " + e.getMessage();
      }
      return null;

    } finally {
      if (_socket == null) {
        try {
          if (sIn != null) sIn.close();
          if (sock != null && !sock.isConnected()) sock.close();
        } catch (IOException e) {
          /* silently ignore close failures; nothing could be done anyway */
        }
      }
    }

    return response;
  }
 @Test
 public void testWorksWithEphemeralPort() throws IOException {
   int assignedPort = server.getLocalPort();
   Socket socket = new Socket("127.0.0.1", assignedPort);
   assertTrue(socket.isConnected());
 }
示例#13
0
 public boolean isConnected() {
   return socket.isConnected();
 }
示例#14
0
 public boolean isConnected() {
   return sock != null && sock.isConnected();
 }
示例#15
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);
    }
  }