Chani
Chani

Reputation: 5175

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.

Upvotes: 0

Views: 545

Answers (1)

OldCurmudgeon
OldCurmudgeon

Reputation: 65879

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

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();}
    };
  }
}

Upvotes: 2

Related Questions