multithreading TCP/IP socket编程中同步传输和异步传输有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17481397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between synchronous and asynchronous transmission in TCP/ IP socket programming?
提问by abhi abhi
I am new to C++ and I am trying to develop a client-server application based on the boost::asio library. I am (still) not able to understand properly the difference between sync and async modes. I've previously studied web protocol services such as HTTP and AJAX. From this explanation, it's clear that HTTP is synchronous and AJAX is asynchronous. What is the difference in TCP socket communication in terms of sync and async? And which mode is better from the perspective of enterprise-level multi-threaded application development, and why?
我是 C++ 新手,我正在尝试开发基于 boost::asio 库的客户端-服务器应用程序。我(仍然)无法正确理解同步和异步模式之间的区别。我以前研究过诸如 HTTP 和 AJAX 之类的 Web 协议服务。从这个解释,很明显 HTTP 是同步的,AJAX 是异步的。TCP 套接字通信在同步和异步方面有什么区别?而从企业级多线程应用开发的角度看,哪种模式更好,为什么?
As I understand synchronous mode, the client blocks for a while until it receives the packet/ data message from the server. And in async mode, the client carries out another operation without blocking the current operation. Why is this different? Is async synonymous with UDP? It seems it doesn't care if it receives transmission acknowledgement.
据我所知,同步模式,客户端会阻塞一段时间,直到它从服务器接收到数据包/数据消息。而在异步模式下,客户端在不阻塞当前操作的情况下执行另一个操作。为什么这是不同的?异步是 UDP 的同义词吗?它似乎并不关心它是否收到传输确认。
回答by user207421
TCP transmission is always asynchronous. What's synchronous or asynchronous is the behaviour of the API. A synchronous API does things while you call it: for example,
send()
moves data to the TCP send buffer and returns when it is done. An asynchronous API starts when you call it, executes independently after it returns to you, and calls you back or provides an interrogable handle via which completion is notified.HTTP is synchronous in the sense that you send a request, receive a response, display or process the response, all in that order.
Ajax is asynchronous only in the sense that it operates independently of the page request/response cycle in the surrounding HTTP request. It's a poor choice of terminology. It would have been better to use a term like 'nested', 'out of band', ...
TCP 传输始终是异步的。同步或异步是 API 的行为。同步 API 会在您调用它时执行某些操作:例如,
send()
将数据移动到 TCP 发送缓冲区并在完成后返回。异步 API 在您调用它时启动,在它返回给您后独立执行,并回调您或提供一个可查询的句柄,通过该句柄通知完成。从您发送请求、接收响应、显示或处理响应的意义上来说,HTTP 是同步的,所有这些都按此顺序进行。
Ajax 的异步性仅在于它独立于周围 HTTP 请求中的页面请求/响应周期运行。这是一个糟糕的术语选择。使用“嵌套”、“带外”等术语会更好......