目前在我的学位中,我们开始使用套接字。
我有几个关于从套接字轮询输入的问题,
使用 select() 函数。
int select( int nfds,
fd_set *readfds,
fd_set *writefds,
fd_set *exceptfds,
const struct timespec *timeout);
是我们想要监控的最大套接字数。我怎样才能只看一个特定的套接字而不是 的范围? 0 到 nfds_val socket ?
为什么我们不能只将“选择”指向相关的套接字结构?
我的意思是除了 绑定(bind) 方法需要这种指针类型 ;)
希望这里有一些专家的回答:)
谢谢你们,祝您度过愉快的一周!
最佳答案
We give select "nfds" param, which would normally would be the maximum sockets number we would like to monitor. How can i watch only one specific socket instead of the range of 0 to nfds_val sockets ?
编辑。 (对不起,这里之前的文字是错误的)只需提供您的套接字
descriptor + 1
.我很确定这并不意味着操作系统会检查 [0, 1... descriptor]
中的所有描述符范围。What are the file descriptors objects that we use? what is their purpose, and why can't we just point "select" to the relevant socket structure?
文件描述符通常是操作系统给用户的整数值。操作系统使用描述符来控制物理和逻辑资源 - 一个文件描述符意味着操作系统为您提供了类似文件的控制。由于 Berkeley Sockets 定义了读写操作,它们是类似文件的,并且套接字对象本质上是纯文件描述符。
接听
why can't we just point "select" to the relevant socket structure?
- 我们实际上可以。传递给 select
的具体内容是什么?取决于操作系统和语言。在 C 中,您将套接字描述符(很可能是简单的 int
值)放入 fd_set
. fd_set
然后传递给 select
.编辑。
Linux的一个小例子:
fd_set set;
FD_ZERO(&set);
FD_SET(socket_fd, &set);
// check if socket_fd is ready for reading
result = select(socket_fd + 1, &set, NULL, NULL, NULL);
if (result == -1) report_error(errno);
Docs.
Windows has similar code.
I've read over the forum regarding Blocking and Non-Blocking mode of select, but couldn't understand the meaning or uses of each, nor how to implement such, would be glad if someone could explain.
一个 阻塞 操作使您的线程等待直到完成。它是您使用的 99% 的功能。如果有套接字准备好进行一些 IO,阻塞
select
将返回 something
立即地。如果没有这样的套接字,线程将等待它们。 非阻塞 select
,在后一种情况下,不会等待,将返回 -1
(错误)。例如,尝试实现能够与多个客户端一起工作的单线程服务器,包括同时发生文件传输等长操作。在这种情况下,您绝对不想使用阻塞套接字操作。
Last but not least (only for the time being :D ) - When binding a socketaddr_in to socket number, why does one needs to cast to socketaddr * and not leave it as sockaddr_in * ? I mean except for the fact that bind method expects this kind of pointer type ;)
可能是由于历史原因,但我不确定。 And there seems to be a fine answer on SO already.
关于sockets - 套接字编程新手,关于 "select()"的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34505393/