Solved

Non-blocking Connect

Posted on 2003-11-06
16
1,372 Views
Last Modified: 2013-11-20
I want to be able to interrupt a connect procedure at any point. In that case...I believe I will have to use the non-blocking version of Connect. (CAsyncSocket::Connect()) So here is my question...how can I create a loop to check for a close flag and/or a completed connection?

0
Comment
Question by:SGyves
  • 7
  • 5
  • 3
  • +1
16 Comments
 
LVL 32

Expert Comment

by:jhance
Comment Utility
I'll go out on a limb here and say that you should NEVER loop checking for a flag in Windows.  That's incredibly bad programming under a message passing system like Windows.

The proper way to do this is to setup your application to receive the FD_CONNECT message which will be sent to your window when a connect happens.
0
 
LVL 12

Expert Comment

by:williamcampbell
Comment Utility
Why dont you spawn the connect procedure in a seperate thread ... then at any time you can simply kill the thred. In you main app you can use AtlWaitWithMessageLoop for the Thread to Finish if your not gATL lookin the ATL soucre for that function and copy and paste the code.
0
 

Author Comment

by:SGyves
Comment Utility
The whole thing is in a separate worker thread....I would just like to kill the thread when I close the document...but I hear that calling killThread is amajor no-no. This worker thread loops for incomming messages sending them to the main thread and checks a document member for things to send. Dont think the notification functions will help me here.
0
 

Author Comment

by:SGyves
Comment Utility
Did I really need to make a separate thread for this socket?? I did have it in the CDoc before. However...I didn't want the call to Connect to block my program if the connection was going to time out. So I talked with some experts on this site...and we agreed that putting it in a separate thread was a good idea. However...I can't stop this case of losing control while my socket is connecting. So I am asking this question. How do I make sure a socket is good to use if I use the non-blocking version of Connect to do that. Is there another solution to my problem that I should take a look at. Please help me.
0
 
LVL 32

Expert Comment

by:jhance
Comment Utility
I did make such a suggestion for you to use async sockets and the messages you'll get when using them but you dismissed that suggestion:

"Dont think the notification functions will help me here."
0
 

Author Comment

by:SGyves
Comment Utility
I can still go back...I have saved my project at every avenue of change...however....I have not gotten an answer for how to see if the socket is ready to use or still trying to connect. I am still open to the possibility...I didn't mean to dismiss your answer...I just go with the answer with the best explanation.
0
 
LVL 32

Accepted Solution

by:
jhance earned 250 total points
Comment Utility
In my opinion, ASYNC sockets are the ONLY way to use sockets under Windows.  The threading of blocking sockets is a "unix" like kludge under Windows where the async sockets model fits in perfectly with the Windows message passing architecture.  Not only that but there is considerable overhead, both in processing and cleanup, when you use the "1 thread per connection" model under Windows.

The best approach is to use the non-blocking asynchronous sockets and setup your application to handle the various messages that will come in as the sockets progress, complete, or fail.  Not only that but you can freely interrupt such sockets any time you like.  Since your Windows application is already setup to handle messges, handing a few additional messages from socket connections is generally no big deal.

In your case, say you have a pending async socket connection that you want to interrupt because it's taking too long.  You simply call closesocket() on the socket handle from your application.  Since your thread of execution is NOT blocked at any time by socket calls, you can do when whenever it seems appropriate.
0
 
LVL 12

Expert Comment

by:williamcampbell
Comment Utility


    Are you using CAsyncSocket?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:SGyves
Comment Utility
jhance...this is great...but I still need to know how my program will know when the connection has been made....does OnConnect() only get called when the connection to the server is complete??? I just need to know how determine weather a socket is ready to use or not.


William...I am using CSocket right now...sometimes I am making calls to the base class AsynchSocket for things like Recieve() so it can check for things being sent to the server even if there is nothing to recieve. But I can easily change everything around to use ASyncSockets....from the way it sounds...I just might move my socket back into the main thread if I can figure out how I can make the main thread know when the connect process is complete and have it do all this with out giving up control to the user.
0
 
LVL 12

Assisted Solution

by:williamcampbell
williamcampbell earned 250 total points
Comment Utility
Yeah there is a callback when the connection is complete or there is a timeout. you can end the session by closing the socket however sometimes this takes a while to timeout.

I would suggest deriving a new class from CAsyncSocket and handling OnConnect

If the socket is a client, connect the socket object to a server socket, using CAsyncSocket::Connect.

If a CAsyncSocket object is in nonblocking mode (operating asynchronously), the call returns immediately and the current error code, retrievable with the GetLastError member function, is WSAEWOULDBLOCK, indicating that the call would have blocked had it not returned immediately because of the mode.

So after you call Connect you wait for OnConnect to be called

void CMyAsyncSocket::OnConnect(int nErrorCode)   // CMyAsyncSocket is
                                                // derived from CAsyncSocket
{
   if (0 != nErrorCode)
   {
      switch( nErrorCode )
      {
          case WSAETIMEDOUT:
            AfxMessageBox("The attempt to connect timed out without
               establishing a connection. \n");
            break;
         default:
            TCHAR szError[256];
            wsprintf(szError, "OnConnect error: %d", nErrorCode);
            AfxMessageBox(szError);
            break;
      }
   }
   CAsyncSocket::OnConnect(nErrorCode);
}

0
 

Author Comment

by:SGyves
Comment Utility
Does OnConnect() only get called once a successful connection is made??? Not just after a call to connect is made right??
0
 

Author Comment

by:SGyves
Comment Utility
Well sweet....I can now eliminate this pain in the arse worker thread I have. This makes my program sooooo much cleaner and easier to manage. The fact that OnConnect gets called after a connection hads either failed or succeeded makes this all sooooo much easier to handle. I am changing it back to have the socket in the main thread with messages. This will thankfully be easy because I have maintained good OOP throughout my development. I will split the points between you two for the great answers. At least I know a heck of a lot more about multithreading because of this...so all is not lost. Thank you both for the help.
0
 
LVL 12

Expert Comment

by:williamcampbell
Comment Utility

  Another Happy Customer :)
0
 

Author Comment

by:SGyves
Comment Utility
Awsome...I have already eliminated two unneeded threads...I have the non-blocking CAsyncSocket up and running and it is soooo much easier to manage. THank you so much. THis would have saved me an incredible ammount of work had I done it this way before.
0
 

Expert Comment

by:Shutterbug
Comment Utility
Wow..what irony... I just posted a question minutes ago, and here I find this thread sitting here, answering my question perfectly! :)  Question wasn't the same... but the answers all fit together.  Thanks :)
0
 
LVL 12

Expert Comment

by:williamcampbell
Comment Utility
Another Happy Customer :)
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction: Load and Save to file, Document-View interaction inside the SDI. Continuing from the second article about sudoku.   Open the project in visual studio. From the class view select CSudokuDoc and double click to open the header …
If you use Adobe Reader X it is possible you can't open OLE PDF documents in the standard. The reason is the 'save box mode' in adobe reader X. Many people think the protected Mode of adobe reader x is only to stop the write access. But this fe…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

743 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now