Re: proper way to close a socket?
Steve,
I read your post but partially addressed it in a reply to another post.
Now I handle the OnConnect() and check if error or no error. If error, I
wrap things up and delete the socket.
But is there any way to safely delete before getting the OnConnect()
callback? The user might get impatient and click the button while waiting.
Will I always always get the OnConnect() with timeout (if there is no port
to connect to)? I could disable the button, but if the callback never comes,
the program will have to be aborted.
For example, if I call Close() even though it hadn't conencted yet, would it
be safe?
Thanks,
Bill
"Stephen Myers" <""StephenMyers\"@discussions@microsoft.com"> wrote in
message news:us7qjoFwKHA.4492@TK2MSFTNGP05.phx.gbl...
Bill Brehm wrote:
I have a problem with CAsynsocket. I can connect to a remote socket. When
I want to close the connection, I just delete the socket object (which
closes the connection) and have no problems.
But if I've started to connect to a remote socket that doesn't exist (or
doesn't accept), and I delete the local socket object while waiting for
the connection, I sometimes get an assert in CAsyncSocket::DoCallBack().
See below. Actually, it's not in the middle of an Accept call because I
test with an address and port that I know doesn't exist.
Any idea how I should be doing this so as not to crash my program?
Thanks,
Bill
void PASCAL CAsyncSocket::DoCallBack(WPARAM wParam, LPARAM lParam)
{
if (wParam == 0 && lParam == 0)
return;
// Has the socket be closed?
CAsyncSocket* pSocket = CAsyncSocket::LookupHandle((SOCKET)wParam,
TRUE);
// If yes ignore message
if (pSocket != NULL)
return;
pSocket = CAsyncSocket::LookupHandle((SOCKET)wParam, FALSE);
if (pSocket == NULL)
{
// Must be in the middle of an Accept call
pSocket = CAsyncSocket::LookupHandle(INVALID_SOCKET, FALSE);
ASSERT(pSocket != NULL);
<-------------------------------------------------asserts here sometimes
but not always.
pSocket->m_hSocket = (SOCKET)wParam;
CAsyncSocket::DetachHandle(INVALID_SOCKET, FALSE);
CAsyncSocket::AttachHandle(pSocket->m_hSocket, pSocket, FALSE);
}
My guess is that the Connect handling is causing the problem. Connect()
will return immediately. You will then get OnConnect(), with or without an
error. The timeout varies, but I would expect it to be on the order of 5
seconds. Once OnConnect has been called you should be able to close the
socket.
HTH
Steve