Reputation: 463
So I've been working on some different networking programs in c++ and I've come across a problem. I use Winsock (version 2) for this, no idea if this is the best thing to use but whatever. So in winsock there is a function to receive a packet (actually 2 functions) and what it does is it waits until it gets a packet and then keeps going, freezing the program while waiting for the packet. What I think I need is some kind of "event" system where there is a function that gets called every time a packet comes in, and the program keeps running while waiting for a packet.
So basically right now if I just want to print the (tcp) packets I'm receiving I have this (first some startup code and creating the sockets and stuff):
char buffer[4096];
while(true){
ZeroMemory(buffer, 4096);
recv(clientSocket, buffer, 4096, 0); //Program freezes until it receives something
std::cout << buffer << std::endl;
}
But what if I have a window that I want to keep updating while waiting for a packet? The program is just going to freeze.
Upvotes: 1
Views: 918
Reputation: 595827
WinSock offers several event-driven models for non-blocking socket operations:
WSAAsyncSelect()
. This would be the easiest way to incorporate into your existing code, since you already have a UI window. You can register your HWND
with the SOCKET
and then add an additional window message handler to handle socket events being sent to the HWND
.
Overlapped I/O or I/O Completion Ports. You can pass WSAOVERLAPPED
structs or callback functions to WSARecv()
and WSASend()
, and you can poll operation statuses via WSAGetOverlappedResult()
or GetQueuedCompletionStatus()
in a timer or thread.
Upvotes: 2