如何在 c++ 中异步发送和接收数据和确认套接字 TCP/IP?
如何在 C++ 套接字 tcp/ip 中异步发送和接收数据和确认?,我可以在我的程序中看到,当发送 145 字节数据 50 次时,我将收到前 6 次的确认,因为需要时间才能给出确认。我尝试等待,直到收到当前发送数据的确认,但这需要很长时间,我不想这样做。我想对数据进行处理。所以我的想法是我将把接收放在一个单独的线程中。我想在发送时同时处理接收?那么异步接收可以工作吗?有人可以帮忙吗?我用来接收和发送数据的类是静态类。因为我需要从其他两个类调用以将数据发送到相同的 ip 和端口。
how to send and receive data and acknowledgement asynchrounously in c++ socket tcp/ip?, i can see in my program as when send some 145 byte data 50 times , i will be receiving the acknowledgement for the first six as it takes time to give the acknowledgement. I have tried waiting until i receive the acknowledgement for the current sent data, but it takes long time , which i dont want to do. I want to process with the data. So what i thought is i will put receive in a separate thread. and i want to process receive simultaneouly while send is happening? So Asynchronous receive will work? Can anyone help? The class which i am using to receive and send data is a static class. As i needed to call from two other classes to send data to same ip and port.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用套接字同时在一个线程中发送数据并在另一线程中接收数据。您不能做的就是从不同线程在同一套接字上执行相同的操作(发送或接收)。
尽管如此,如果不必要,请始终尽量避免添加新线程。您可以使用一些套接字函数(选择,WSAEventSelect)将通知当您可以在套接字上执行读/写操作时。将它们放入单个线程中的循环中,等待事件并处理它们 - 在同一线程中读/写。如果您需要处理接收到的数据并且这需要时间,请将接收到的数据存储在与另一个数据处理线程共享的队列中。当然,请记住,您需要使该队列线程安全并同步套接字和数据处理线程。
You can use socket for sending data in one thread and for receiving data in another thread, simultaneously. The thing you cannot do is performing the same action (sending or receiving) on the same socket from different threads.
Nevertheless, always try to avoid adding new threads if unnecessary. You can use some socket functions (select, WSAEventSelect) that will notify you when you can perform read/write on the socket. Put them in a loop in a single thread, wait for events and handle them - read/write in the same thread. If you need to process received data and that takes time, store received data in a queue shared with another, data processing thread. Of course, bear in mind you would need to make this queue thread-safe and synchronise socket and data processing thread.
如果在 Posix 系统上,您可能需要一个多路复用系统调用,例如 poll 或
ppoll
或pselect
或select
如果您的系统不是 Posix(例如 Windows),您应该找到一些类似的功能,或使用线程。
If on Posix systems, you might need a multiplexing system call like poll or
ppoll
orpselect
orselect
If your system is non-Posix (e.g. windows) you should find some similar functionality, or use threads.