Reputation: 53
I want a server to accept a client with this code
SOCKADDR_IN cliaddr = { 0 };
int len = sizeof(cliaddr);
_sockClient = accept(_sockServer, (SOCKADDR*)&cliaddr, &len);
Both _sockClient and _sockServer are SOCKETs, _sockServer's SOCKET already connected to the server.
Before I accept, I want to check _sockServer
if there is an incoming client request to join. I'm pretty sure there is a way to do this, though I don't know how. Does anyone know?
Upvotes: 1
Views: 588
Reputation: 598134
By default, a socket operates in blocking mode. So, you could simply call accept()
and let it block the calling thread until a new connection is accepted. That is the easiest approach. If you don't want to block the calling thread, you could call accept()
in another thread instead.
But, provided you don't want to block any thread at all, then yes, there are other ways to handle this, depending on your programming model:
Poll the socket using the readfds
parameter of select()
. The socket will be in a readable state if it has any pending connections waiting to be accepted.
Use WSAEventSelect()
to signal a waitable WSAEVENT
object whenever an FD_ACCEPT
event occurs, indicating that pending connections are available to accept. You can then poll/wait on that object using WSAWaitForMultipleEvents()
, and use WSAEnumNetworkEvents()
to reset the object's state for the next wait.
Use WSAAsyncSelect()
to receive a window message whenever an FD_ACCEPT
event occurs.
Use AcceptEx()
instead of accept()
to start an asynchronous acceptance in the background. It will report its completion to you via Overlapped I/O or an I/O Completion Port.
See Overlapped I/O and Event Objects in Winsock's documentation for more details.
Upvotes: 3