简体   繁体   中英

How to make the same program act like a server and client (using sockets in java)

How can I send and receive from the same program in java ? To make matters worse, I need to do both in the same time in parallel.

You need a well behaved queue such as a BlockingQueue between two Thread s.

public class TwoThreads {
  static final String FINISHED = "Finished";
  public static void main(String[] args) throws InterruptedException {
    // The queue
    final BlockingQueue<String> q = new ArrayBlockingQueue<String>(10);
    // The sending thread.
    new Thread() {
      @Override
      public void run() {
        String message = "Now is the time for all good men to come to he aid of the party.";
        try {
          // Send each word.
          for (String word : message.split(" ")) {
            q.put(word);
          }
          // Then the terminator.
          q.put(FINISHED);
        } catch (InterruptedException ex) {
          Thread.currentThread().interrupt();
        }
      }
      { start();}
    };
    // The receiving thread.
    new Thread() {
      @Override
      public void run() {
        try {
          String word;
          // Read each word until finished is detected.
          while ((word = q.take()) != FINISHED) {
            System.out.println(word);
          }
        } catch (InterruptedException ex) {
          Thread.currentThread().interrupt();
        }
      }
      { start();}
    };
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM