How can I do asynchronous socket proramming in console application?  
Author Message
Sushantp





PostPosted: Visual C++ General, How can I do asynchronous socket proramming in console application? Top

I was trying with using WSAAsyncSelect, but it requires handle parameter of the window to which the message will be sent when an event occurs.
So how can I get handle of a console application
Or there is some other way to do asynchronous socket programming in console application.
Thanks.



Visual C++12  
 
 
Viorel.





PostPosted: Visual C++ General, How can I do asynchronous socket proramming in console application? Top

Maybe you should consider an alternative solution based on events. First create an event using WSACreateEvent or CreateEvent function. Then associate this event with network event using WSAEventSelect function. After this you can check or wait for network events using WaitForSingleObject or WaitForMultipleObjects functions.

 

You can also use CSocket or CAsyncSocket class from MFC library, which creates for you a hidden window as a target for network messages.

 

I hope this makes sense.


 
 
Sushantp





PostPosted: Visual C++ General, How can I do asynchronous socket proramming in console application? Top

Thanks, I will check with creating events.

 
 
Sushantp





PostPosted: Visual C++ General, How can I do asynchronous socket proramming in console application? Top

I tried with following code...

fd_mail = socket(AF_INET, SOCK_STREAM, 0);
host_info.sin_family = AF_INET;
host_info.sin_port = htons (110);
host_info.sin_addr.s_addr = inet_addr(IPAddr);

// Setup socket for asynchronous operation
async_event = WSACreateEvent();
if(WSAGetLastError() != 0)
return -1;
int t = WSAEventSelect(fd_mail, async_event, FD_CONNECT | FD_READ | FD_WRITE | FD_CLOSE);
int err = 1;
err_code = connect(fd_mail, (struct sockaddr *)&host_info, (sizeof(struct sockaddr_in)));

And before calling recv() for response from mail server which reads mail content
I am using this statement
DWORD ret = WaitForSingleObject(async_event, 1000);

I just cant understand how this mechanism works..

 
 
Viorel.





PostPosted: Visual C++ General, How can I do asynchronous socket proramming in console application? Top

The wait function returns WSA_WAIT_EVENT_0 if one of network events occurred during 1 second interval, i.e. the host is ready for reading or writing, or closed the socket. Otherwise it returns WSA_WAIT_TIMEOUT after 1 second. In order to determine which of events occurred, try WSAEnumNetworkEvents. If you need just to check the readiness without waiting, then specify zero timeout.

Probably you can obtain more precise information in MSDN or at http://www.sockaddr.com/ExampleSourceCode.html or http://www.codeproject.com/internet/networkevents.asp.