繁体   English   中英

有人可以用WinSock解释可写和可读fd_sets的功能吗?

[英]Can someone explain the function of writeable and readable fd_sets with WinSock?

我正在为一个大学项目编写网络游戏,并且在客户端和服务器之间收发消息时,我不确定如何实现writeable fd_set(我的讲师的示例代码仅包含readable fd_set)以及两个带有select() fd_sets的功能是什么。 您可以提供的任何见解都将有助于我理解这一点。

我的服务器代码是这样的:

bool ServerSocket::Update() {
    // Update the connections with the server

    fd_set readable;
    FD_ZERO(&readable);

    // Add server socket, which will be readable if there's a new connection
    FD_SET(m_socket, &readable);

    // Add connected clients' sockets
    if(!AddConnectedClients(&readable)) {
        Error("Couldn't add connected clients to fd_set.");
        return false;
    }

    // Set timeout to wait for something to happen (0.5 seconds)
    timeval timeout;
    timeout.tv_sec = 0;
    timeout.tv_usec = 500000;

    // Wait for the socket to become readable
    int count = select(0, &readable, NULL, NULL, &timeout);
    if(count == SOCKET_ERROR) {
        Error("Select failed, socket error.");
        return false;
    }

    // Accept new connection to the server socket if readable
    if(FD_ISSET(m_socket, &readable)) {
        if(!AddNewClient()) {
            return false;
        }
    }

    // Check all clients to see if there are messages to be read
    if(!CheckClients(&readable)) {
        return false;
    }

    return true;
}

您将创建一个名为writeablefd_set变量,以相同的方式(使用相同的套接字)对其进行初始化,并将其作为select的第三个参数传递:

select(0, &readable, &writeable, NULL, &timeout);

然后在select返回之后,您将检查每个套接字是否仍在set writeable 如果是这样,那么它是可写的。

基本上, readable工作方式完全相同,只是它告诉您有关套接字的另一件事。

套接字变为:

  • 如果套接字接收缓冲区中有数据或挂起的FIN( recv()将返回零),则可读
  • 如果套接字接收缓冲区中有空间,则可写。 请注意,几乎所有时间都是如此,因此,只有在套接字上遇到先前的EWOULDBLOCK / EAGAIN时,才应使用它;否则,则不要使用它。

select()已经过时了,它的界面很神秘。 poll (或者它是Windows的对应WSAPoll是它的现代替代品,应始终首选。

它将以以下方式使用:

WSAPOLLFD pollfd = {m_socket, POLLWRNORM, 0};
int rc = WSAPoll(&pollfd, 1, 100);
if (rc == 1) {
   // Socket is ready for writing!
}

暂无
暂无

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

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