+ // Get the active event loop which we'll use for the message dispatching
+ // when running in the main thread
+ wxEventLoopBase *eventLoop;
+ if ( wxIsMainThread() )
+ {
+ eventLoop = wxEventLoop::GetActive();
+
+#ifdef __WXMSW__
+ wxASSERT_MSG( eventLoop,
+ "Sockets won't work without a running event loop" );
+#endif // __WXMSW__
+ }
+ else // in worker thread
+ {
+ // We never dispatch messages from threads other than the main one.
+ eventLoop = NULL;
+ }
+
+ // Wait in an active polling loop: notice that the loop is executed at
+ // least once, even if timeout is 0 (i.e. polling).
+ bool gotEvent = false;
+ for ( ;; )
+ {
+ // We always stop waiting when the connection is lost as it doesn't
+ // make sense to continue further, even if GSOCK_LOST_FLAG is not
+ // specified in flags to wait for.
+ const GSocketEventFlags
+ result = m_socket->Select(flags | GSOCK_LOST_FLAG);
+
+ // Incoming connection (server) or connection established (client)?
+ if ( result & GSOCK_CONNECTION_FLAG )
+ {
+ m_connected = true;
+ m_establishing = false;
+ gotEvent = true;
+ break;
+ }
+
+ // Data available or output buffer ready?
+ if ( (result & GSOCK_INPUT_FLAG) || (result & GSOCK_OUTPUT_FLAG) )
+ {
+ gotEvent = true;
+ break;
+ }
+
+ // Connection lost
+ if ( result & GSOCK_LOST_FLAG )
+ {
+ m_connected = false;
+ m_establishing = false;
+ if ( flags & GSOCK_LOST_FLAG )
+ gotEvent = true;
+ break;
+ }
+
+ if ( m_interrupt )
+ break;
+
+ // Wait more?
+ const wxMilliClock_t timeNow = wxGetLocalTimeMillis();
+ if ( timeNow >= timeEnd )
+ break;
+
+ if ( eventLoop )
+ {
+ // Dispatch the events when we run in the main thread and have an
+ // active event loop: without this sockets don't work at all under
+ // MSW as socket flags are only updated when socket messages are
+ // processed.
+ if ( eventLoop->Pending() )
+ eventLoop->Dispatch();
+ }
+#if wxUSE_THREADS
+ else // no event loop or waiting in another thread
+ {
+ // We're busy waiting but at least give up the rest of our current
+ // time slice.
+ wxThread::Yield();
+ }
+#endif // wxUSE_THREADS
+ }