C语言 什么是异步套接字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2331869/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:36:28  来源:igfitidea点击:

What are Async Sockets?

csocketsasynchronous

提问by Jay

What are Async Sockets? How are they different from normal sockets (Blocking and Non-Blocking)?

什么是异步套接字?它们与普通套接字(阻塞和非阻塞)有何不同?

Any pointers in that direction or any links to tutorials will be helpful.

任何指向该方向的指针或任何教程链接都会有所帮助。

Thanks.

谢谢。

回答by qrdl

There are three ways to communicate with sockets in async way:

以异步方式与套接字通信的方式有以下三种:

  1. Open regular socket, but do not read from it (because read()blocks) until you know there it something to be read. You can use select()or poll()to check whether there are data to read from socket(s), and if there is something, read it, as read()won't block.

  2. Switch socket to non-blocking I/O, by setting O_NONBLOCKflag with fcntl()function. In this case read()won't block.

  3. Set socket's O_ASYNCflag using FIOASYNCoption of ioctl()(see man 7 socketfor details). In this case you will receive SIGIOsignal when there is something to read from socket.

  1. 打开常规套接字,但不要从中读取(因为read()阻塞),直到您知道要读取的内容。您可以使用select()poll()来检查是否有要从套接字读取的数据,如果有,则读取它,因为read()不会阻塞。

  2. 通过O_NONBLOCK使用fcntl()函数设置标志,将套接字切换到非阻塞 I/O 。在这种情况下read()不会阻塞。

  3. O_ASYNC使用FIOASYNC选项设置套接字的标志ioctl()man 7 socket有关详细信息,请参阅)。在这种情况下,SIGIO当有内容要从套接字读取时,您将收到信号。

Third approach is async socket.

第三种方法是异步套接字。

回答by Andy

Comparison of the following five different models for I/O in UNIX Network Programming: The sockets networking APIwould be helpful:

UNIX 网络编程中I/O 的以下五种不同模型的比较:套接字网络 API会有所帮助:

Blocking

阻塞

Nonblocking

非阻塞

I/O multiplexing

输入/输出复用

Signal-driven I/O

信号驱动的 I/O

Asynchronous I/O

异步输入/输出

回答by Warty

If a server uses a synchronous socket, while it is waiting for data from the client, its main thread is blocked, so the server won't be doing anything... that is bad if you have multiple clients connecting. In an asynchronous socket, you CAN do other stuff while waiting for the client to send data to you, so now you CAN have multiple clients connecting to you

如果服务器使用同步套接字,当它等待来自客户端的数据时,它的主线程被阻塞,所以服务器不会做任何事情……如果你有多个客户端连接,这很糟糕。在异步套接字中,您可以在等待客户端向您发送数据的同时做其他事情,所以现在您可以有多个客户端连接到您

Synchronous uses a function like receive() which blocks until it gets a message

Synchronous 使用了像 receive() 这样的函数,它会阻塞直到收到消息

Asynchronous has beginReceive() endReceive() or similar functions. It uses callbacks, when a message is received, the callback is invoked

异步有 beginReceive() endReceive() 或类似的函数。它使用回调,当收到消息时,调用回调