简体   繁体   English

通过UDP并发接收和发送数据

[英]Concurrent Receiving and Sending of Data over UDP

I am trying to write a program that constantly listens for packets over UDP, but also periodically sends out data over UDP (every x seconds). 我正在尝试编写一个程序,该程序不断侦听UDP上的数据包,但还定期通过UDP发送数据(每隔x秒)。 The tricky part is the data I receive will change the data I send out, so I don't think I can simply do one of the tasks in a separate thread. 棘手的部分是我接收到的数据将更改我发送的数据,因此我认为我不能简单地在单独的线程中执行一项任务。 I also can't afford to have any blocking. 我也承受不起任何阻碍。 I was hoping someone could give me a push in the right direction. 我希望有人能给我正确的方向。 If it's relevant, I am programming in Java, and will be sending and receiving data with multiple clients at a time. 如果相关的话,我正在用Java编程,并且将一次与多个客户端发送和接收数据。

I don't think I can simply do one of the tasks in a separate thread. 我认为我无法在单独的线程中简单地完成一项任务。

You can still have the recv and send in separate threads. 您仍然可以使用recv并在单独的线程中发送。 But they cannot happen asynchronously. 但是它们不能异步发生。 If the data that you send out is going to depend on the data that you receive, then you cannot have the send/recv asynchronously. 如果您发送的数据将取决于您接收的数据,那么您将无法异步进行发送/接收。 This is a request/response model. 这是一个请求/响应模型。 The response has to be sent only after receving the request. 仅在接收到请求后才发送响应。

I also can't afford to have any blocking 我也承受不起任何阻碍

You can still have the sockets set for non-blocking 您仍然可以将套接字设置为非阻塞

While you could use separate threads, you can do this single-threaded with a simple timeout associated with your socket: 虽然可以使用单独的线程,但是可以通过与套接字相关的简单超时来执行此单线程操作:

Follow the example here: 请在此处遵循示例:

set timeout for socket receive 设置套接字接收超时

When the socket throws a timeout exception, you do your periodic send, then go back to receiving data on the socket. 当套接字抛出超时异常时,您将进行定期发送,然后返回到在套接字上接收数据。

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

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