繁体   English   中英

如何使相同的程序像服务器和客户端一样(在java中使用套接字)

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

如何从java中的同一程序发送和接收? 更糟糕的是,我需要在同一时间同时做两件事。

您需要一个行为良好的队列,例如两个Thread之间的BlockingQueue

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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