使用Datagram UDP发送和接收确认

时间:2012-10-23 22:34:39

标签: java multithreading sockets networking udp

我不熟悉套接字编程和编程Java UDP简单客户端 - 服务器应用程序。我正在写一个时间/日期服务器客户端。客户端可以向服务器询问时间和日期,并等待响应。此外,服务器每分钟都会使用当前时间更新所有客户端。客户需要

  1. 能够启动与服务器的联系并等待回复消息

  2. 侦听来自服务器的定期更新

  3. 如何使用单个DatagramSocket执行此操作?

    我在考虑创建两个线程:一个是侦听,另一个是写入。问题是,在客户端启动与服务器的联系的情况下,它需要等待从服务器接收确认。因此,写入线程有时也需要从服务器侦听数据包。但在这种情况下,我有两个线程正在侦听,错误的线程将得到确认。

    有没有办法指定哪个线程获得输入?或者还有其他方法可以解决这个问题吗?

    我一直在寻找这个答案但却无法找到它。我发现的最近的是Java sockets: can you send from one thread and receive on another?

1 个答案:

答案 0 :(得分:0)

如果只有一个编写器线程,那么它可以发送请求并进入等待循环。然后,侦听器线程将获得响应,将其添加到共享变量(可能是AtomicReference),然后通知作者已收到响应。

  // both write and listener threads will need to share this
  private final AtomicReference<Response> responseRef =
     new AtomicReference<Response>();
  ...
  // writer-thread
  writeRequest(request);
  synchronize (responseRef) {
     while (responseRef.get() == null) {
        // maybe put a timeout here
        responseRef.wait();
     }
  }
  processResponse(response);
  ...

  // listener-thread
  Response response = readResponse();
  synchronize (responseRef) {
     responseRef.set(response);
     responseRef.notify();
  }

如果您同时发送多个编写器或多个请求,则会变得更复杂。您需要为每个请求发送某种唯一ID,并在响应中返回它。然后响应线程可以将请求与响应匹配。您需要ConcurrentHashMap或其他共享集合,以便响应者可以匹配特定请求,添加响应,并通知相应的等待线程。