gpt4 book ai didi

c - 使用事件驱动套接字时如何生成网络事件 FD_WRITE?

转载 作者:可可西里 更新时间:2023-11-01 14:14:55 24 4
gpt4 key购买 nike

我正在开发基于 newtwork 事件的套接字应用程序。

当客户端发送了一些数据并且套接字上有一些东西需要读取时,产生FD_READ网络事件。

现在根据我的理解,当服务器想要写入套接字时,必须有一个事件产生,即FD_WRITE。但是这个消息将如何产生呢?

当有可读取的内容时,会自动生成 FD_READ,但是当服务器要写入内容时,FD_WRITE 怎么办?

谁能帮我解决这个困惑?

以下是代码片段:

WSAEVENT hEvent = WSACreateEvent();
WSANETWORKEVENTS events;
WSAEventSelect(newSocketIdentifier, hEvent, FD_READ | FD_WRITE);

while(1)
{ //while(1) starts
waitRet = WSAWaitForMultipleEvents(1, &hEvent, FALSE, WSA_INFINITE, FALSE);
//WSAResetEvent(hEvent);
if(WSAEnumNetworkEvents(newSocketIdentifier,hEvent,&events) == SOCKET_ERROR)
{
//Failure
}
else
{ //else event occurred starts
if(events.lNetworkEvents & FD_READ)
{
//recvfrom()
}
if(events.lNetworkEvents & FD_WRITE)
{
//sendto()
}
}
}

最佳答案

FD_WRITE 表示您可以立即写入套接字。如果发送缓冲区满了(你发送数据的速度比它在网络上发送的速度快),最终你将无法再写入,直到你稍等片刻。

一旦您的写入因缓冲区已满而失败,此消息将发送给您,让您知道您可以重试该发送。

它也会在您第一次打开套接字时发送,让您知道它在那里并且您可以开始写入。

http://msdn.microsoft.com/en-us/library/windows/desktop/ms741576(v=vs.85).aspx

The FD_WRITE network event is handled slightly differently. An FD_WRITE network event is recorded when a socket is first connected with a call to the connect, ConnectEx, WSAConnect, WSAConnectByList, or WSAConnectByName function or when a socket is accepted with accept, AcceptEx, or WSAAccept function and then after a send fails with WSAEWOULDBLOCK and buffer space becomes available. Therefore, an application can assume that sends are possible starting from the first FD_WRITE network event setting and lasting until a send returns WSAEWOULDBLOCK. After such a failure the application will find out that sends are again possible when an FD_WRITE network event is recorded and the associated event object is set.

因此,理想情况下,您现在可能会保留一个标志,判断是否可以写作。它开始为 true,但最终,您在调用 sendto 时得到一个 WSAEWOULDBLOCK,并将其设置为 false。收到 FD_WRITE 后,您将标志设置回 true 并继续发送数据包。

关于c - 使用事件驱动套接字时如何生成网络事件 FD_WRITE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16479106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com