?
Solved

CAsyncSocket problem

Posted on 2007-09-29
8
Medium Priority
?
866 Views
Last Modified: 2013-12-14
I'm using CAsyncSocket in a Dialog app to communicate with network devices.  The problem I am having is it throwing an exception when I call sock.Close() (if the socket creation/connection has failed).  Because its async I dont wait around for it to connect... it gives me the WSAEWOULDBLOCK error which is to be expected.  However at some point the connection times out, and in my restart code I call 'Close()' to clean up the socket.  If the original connection failed it throws an exception.

I also get an exception if the Create call was successful, then the Connect failed, then I call Create again.

So basically I need a failsafe Close() call that I can make, or a way to avoid these exceptions (BTW Try Catch does not help).
0
Comment
Question by:pmartino99
  • 4
  • 2
7 Comments
 
LVL 12

Expert Comment

by:OnegaZhang
ID: 19986466
I guess you are running Debug build. When connect is failed, there is nothing to close, so Debug version will warn you.
To get a workaround, you may check validity of your socket (against INVALID_SOCKET) before close.
 
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 19990558
You could catch the exceptions (and ignore) if you are not interested in handling them:

  try
  {
       m_sock.Close();
  }
  catch(...)
  {
  }

Regards, Alex
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 19990610
>>>> Because its async I dont wait around for it to connect..

You could make a own class that manages the status of the socket.

enum SocketStatus { SOCK_UNDEFINED, SOCK_CREATED, SOCK_BOUND,
                                  SOCK_LISTENING, SOCK_CONNECTED, SOCK_DISCONNECTED};

class MySocket : public CAsyncSocket
{
       SocketStatus  m_status;
public:
       SocketStatus  getStatus() { return m_status; }
       SocketStatus  setStatus(SocketStatus status  )
       { SocketStatus stat = m_status; m_status = status; return stat; }
     
};

You could use the MySocket instead of CAsyncSocket and track the status with the appropriate handlers, e. g. the OnConnect would set the status to SOCK_CONNECTED. So, before closing you could check whether the socket was connected.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:pmartino99
ID: 19993324
After some trial and error I believe the problem lies with passing the socket handle from the main class to the thread.  MS says you can't do this and must instead Detach then Re-Attach (http://support.microsoft.com/kb/q175668/).  This adds a lot of complexity to an already-complex operation, so I have changed it not to have to use the sockets in the thread.

If anyone has experience with this I'd love to hear about it... basically the problem is a Ping function I call to verify the online connection takes a few seconds to complete, so it bogs down my program.  I wanted to put the ping/socket create/socket connect/send command through socket into a threaded function, but this passing problem makes that very tricky.
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 19994273
>>>> the problem lies with passing the socket handle from the main class to the thread.

If using threads you should omit the CAsyncSocket and use native winsock instead. The main benefit of CAsyncThread is to synchronize asynchronously happening socket events into the normal message queue. If using threads you actually don't need that. The thread can run an infinite loop which both reads from the socket when a select with timeout tells that there is something to read (so avoid blocking) *and* sends messages or disconnects within the same loop by evaluating a queue.

    while (!thread->stopflag)
    {
           ...
           int ret = select( ... readsocket ... timeout );
           if (ret == 0)
           {
                   int bytesread = recv(readsocket ...);
                   ...
                   thread->dlg->PostMessage(MY_MSG_READ, 0, (LPARAM)thread);
            }
            if (!thread->isJobqueueEmpty())
            {
                    Job* job = thread->popJobFromQueue();
                    if (job != NULL)
                          job->do(thread);  // send or disconnect
            }
       }
   }


In the above code the thread would communicate with the main (GUI) thread via PostMessage and would get requests from the GUI via a 'job queue' managed by a private thread class.

Regards, Alex


 
0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 375 total points
ID: 20852502
>>>> with some or all of the points refunded to the Asker's account

Hmmm. I made a few suggestions but not really got a feedback. The asker seems to have some preferences which may work or may not work. I couldn't help him with this as there was no code and I actually think that MFC socket classes is not the right approach.

Regards, Alex
0
 

Author Closing Comment

by:pmartino99
ID: 31429804
Thanks... it wasn't exactly what I wanted but it was good information.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to install Selenium IDE and loops for quick automated testing. Get Selenium IDE from http://seleniumhq.org Go to that link and select download selenium in the right hand column That will then direct you to their download page. From that p…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question