1 ///////////////////////////////////////////////////////////////////////////// 
   2 // Name:       src/common/socket.cpp 
   3 // Purpose:    Socket handler classes 
   4 // Authors:    Guilhem Lavaux, Guillermo Rodriguez Garcia 
   6 // Copyright:  (C) 1999-1997, Guilhem Lavaux 
   7 //             (C) 2000-1999, Guillermo Rodriguez Garcia 
   9 // License:    wxWindows licence 
  10 ///////////////////////////////////////////////////////////////////////////// 
  12 // ========================================================================== 
  14 // ========================================================================== 
  16 // For compilers that support precompilation, includes "wx.h". 
  17 #include "wx/wxprec.h" 
  25 #include "wx/socket.h" 
  28     #include "wx/object.h" 
  29     #include "wx/string.h" 
  36     #include "wx/module.h" 
  39 #include "wx/apptrait.h" 
  40 #include "wx/sckaddr.h" 
  41 #include "wx/stopwatch.h" 
  42 #include "wx/thread.h" 
  43 #include "wx/evtloop.h" 
  45 // DLL options compatibility check: 
  47 WX_CHECK_BUILD_OPTIONS("wxNet") 
  49 // -------------------------------------------------------------------------- 
  50 // macros and constants 
  51 // -------------------------------------------------------------------------- 
  54 #define MAX_DISCARD_SIZE (10 * 1024) 
  56 #define wxTRACE_Socket _T("wxSocket") 
  58 // -------------------------------------------------------------------------- 
  60 // -------------------------------------------------------------------------- 
  62 IMPLEMENT_CLASS(wxSocketBase
, wxObject
) 
  63 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
) 
  64 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
) 
  65 IMPLEMENT_CLASS(wxDatagramSocket
, wxSocketBase
) 
  66 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
) 
  68 // -------------------------------------------------------------------------- 
  70 // -------------------------------------------------------------------------- 
  72 class wxSocketState 
: public wxObject
 
  75   wxSocketFlags            m_flags
; 
  76   wxSocketEventFlags       m_eventmask
; 
  81   wxSocketState() : wxObject() {} 
  83   DECLARE_NO_COPY_CLASS(wxSocketState
) 
  86 // ============================================================================ 
  88 // ============================================================================ 
  90 GSocketManager 
*GSocketManager::ms_manager 
= NULL
; 
  93 void GSocketManager::Set(GSocketManager 
*manager
) 
  95     wxASSERT_MSG( !ms_manager
, "too late to set manager now" ); 
 101 void GSocketManager::Init() 
 103     wxASSERT_MSG( !ms_manager
, "shouldn't be initialized twice" ); 
 106         Details: Initialize() creates a hidden window as a sink for socket 
 107         events, such as 'read completed'. wxMSW has only one message loop 
 108         for the main thread. If Initialize is called in a secondary thread, 
 109         the socket window will be created for the secondary thread, but 
 110         since there is no message loop on this thread, it will never 
 111         receive events and all socket operations will time out. 
 112         BTW, the main thread must not be stopped using sleep or block 
 113         on a semaphore (a bad idea in any case) or socket operations 
 116         On the Mac side, Initialize() stores a pointer to the CFRunLoop for 
 117         the main thread. Because secondary threads do not have run loops, 
 118         adding event notifications to the "Current" loop would have no 
 119         effect at all, events would never fire. 
 121     wxASSERT_MSG( wxIsMainThread(), 
 122                     "sockets must be initialized from the main thread" ); 
 124     wxAppConsole 
* const app 
= wxAppConsole::GetInstance(); 
 125     wxCHECK_RET( app
, "sockets can't be initialized without wxApp" ); 
 127     ms_manager 
= app
->GetTraits()->GetSocketManager(); 
 130 // ========================================================================== 
 132 // ========================================================================== 
 134 // -------------------------------------------------------------------------- 
 135 // Initialization and shutdown 
 136 // -------------------------------------------------------------------------- 
 138 // FIXME-MT: all this is MT-unsafe, of course, we should protect all accesses 
 139 //           to m_countInit with a crit section 
 140 size_t wxSocketBase::m_countInit 
= 0; 
 142 bool wxSocketBase::IsInitialized() 
 144     return m_countInit 
> 0; 
 147 bool wxSocketBase::Initialize() 
 149     if ( !m_countInit
++ ) 
 151         if ( !GSocket_Init() ) 
 162 void wxSocketBase::Shutdown() 
 164     // we should be initialized 
 165     wxASSERT_MSG( m_countInit 
> 0, _T("extra call to Shutdown()") ); 
 166     if ( --m_countInit 
== 0 ) 
 172 // -------------------------------------------------------------------------- 
 174 // -------------------------------------------------------------------------- 
 176 void wxSocketBase::Init() 
 179   m_type         
= wxSOCKET_UNINIT
; 
 191   m_beingDeleted 
= false; 
 205   if ( !IsInitialized() ) 
 207       // this Initialize() will be undone by wxSocketModule::OnExit(), all the 
 208       // other calls to it should be matched by a call to Shutdown() 
 213 wxSocketBase::wxSocketBase() 
 218 wxSocketBase::wxSocketBase(wxSocketFlags flags
, wxSocketType type
) 
 226 wxSocketBase::~wxSocketBase() 
 228   // Just in case the app called Destroy() *and* then deleted 
 229   // the socket immediately: don't leave dangling pointers. 
 230   wxAppTraits 
*traits 
= wxTheApp 
? wxTheApp
->GetTraits() : NULL
; 
 232       traits
->RemoveFromPendingDelete(this); 
 234   // Shutdown and close the socket 
 238   // Destroy the GSocket object 
 242   // Free the pushback buffer 
 247 bool wxSocketBase::Destroy() 
 249   // Delayed destruction: the socket will be deleted during the next 
 250   // idle loop iteration. This ensures that all pending events have 
 252   m_beingDeleted 
= true; 
 254   // Shutdown and close the socket 
 257   // Supress events from now on 
 260   // schedule this object for deletion 
 261   wxAppTraits 
*traits 
= wxTheApp 
? wxTheApp
->GetTraits() : NULL
; 
 264       // let the traits object decide what to do with us 
 265       traits
->ScheduleForDestroy(this); 
 267   else // no app or no traits 
 269       // in wxBase we might have no app object at all, don't leak memory 
 276 // -------------------------------------------------------------------------- 
 278 // -------------------------------------------------------------------------- 
 280 // The following IO operations update m_error and m_lcount: 
 281 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard} 
 283 // TODO: Should Connect, Accept and AcceptWith update m_error? 
 285 bool wxSocketBase::Close() 
 287   // Interrupt pending waits 
 293     m_socket
->UnsetCallback(GSOCK_INPUT_FLAG 
| GSOCK_OUTPUT_FLAG 
| 
 294                                     GSOCK_LOST_FLAG 
| GSOCK_CONNECTION_FLAG
); 
 296     // Shutdown the connection 
 297     m_socket
->Shutdown(); 
 301   m_establishing 
= false; 
 305 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
) 
 310   m_lcount 
= _Read(buffer
, nbytes
); 
 312   // If in wxSOCKET_WAITALL mode, all bytes should have been read. 
 313   if (m_flags 
& wxSOCKET_WAITALL
) 
 314     m_error 
= (m_lcount 
!= nbytes
); 
 316     m_error 
= (m_lcount 
== 0); 
 318   // Allow read events from now on 
 324 wxUint32 
wxSocketBase::_Read(void* buffer_
, wxUint32 nbytes
) 
 326   char *buffer 
= (char *)buffer_
; 
 330   // Try the pushback buffer first 
 331   total 
= GetPushback(buffer
, nbytes
, false); 
 333   buffer  
= (char *)buffer 
+ total
; 
 335   // Return now in one of the following cases: 
 336   // - the socket is invalid, 
 337   // - we got all the data 
 342   // Possible combinations (they are checked in this order) 
 344   // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK) 
 349   if (m_flags 
& wxSOCKET_NOWAIT
) 
 351     m_socket
->SetNonBlocking(1); 
 352     ret 
= m_socket
->Read(buffer
, nbytes
); 
 353     m_socket
->SetNonBlocking(0); 
 360   else // blocking socket 
 364       // dispatch events unless disabled 
 365       if ( !(m_flags 
& wxSOCKET_BLOCK
) && !WaitForRead() ) 
 368       ret 
= m_socket
->Read(buffer
, nbytes
); 
 371           // for connection-oriented (e.g. TCP) sockets we can only read 0 
 372           // bytes if the other end has been closed, and for connectionless 
 373           // ones (UDP) this flag doesn't make sense anyhow so we can set it to 
 374           // true too without doing any harm 
 381           // this will be always interpreted as error by Read() 
 387       // if wxSOCKET_WAITALL is not set, we can leave now as we did read 
 389       if ( !(m_flags 
& wxSOCKET_WAITALL
) ) 
 392       // otherwise check if read the maximal requested amount of data 
 397       // we didn't, so continue reading 
 398       buffer  
= (char *)buffer 
+ ret
; 
 405 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
) 
 407   wxUint32 len
, len2
, sig
, total
; 
 412     unsigned char sig
[4]; 
 413     unsigned char len
[4]; 
 422   SetFlags((m_flags 
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
); 
 424   if (_Read(&msg
, sizeof(msg
)) != sizeof(msg
)) 
 427   sig 
= (wxUint32
)msg
.sig
[0]; 
 428   sig 
|= (wxUint32
)(msg
.sig
[1] << 8); 
 429   sig 
|= (wxUint32
)(msg
.sig
[2] << 16); 
 430   sig 
|= (wxUint32
)(msg
.sig
[3] << 24); 
 432   if (sig 
!= 0xfeeddead) 
 434     wxLogWarning(_("wxSocket: invalid signature in ReadMsg.")); 
 438   len 
= (wxUint32
)msg
.len
[0]; 
 439   len 
|= (wxUint32
)(msg
.len
[1] << 8); 
 440   len 
|= (wxUint32
)(msg
.len
[2] << 16); 
 441   len 
|= (wxUint32
)(msg
.len
[3] << 24); 
 451   // Don't attemp to read if the msg was zero bytes long. 
 454     total 
= _Read(buffer
, len
); 
 461     char *discard_buffer 
= new char[MAX_DISCARD_SIZE
]; 
 464     // NOTE: discarded bytes don't add to m_lcount. 
 467       discard_len 
= ((len2 
> MAX_DISCARD_SIZE
)? MAX_DISCARD_SIZE 
: len2
); 
 468       discard_len 
= _Read(discard_buffer
, (wxUint32
)discard_len
); 
 469       len2 
-= (wxUint32
)discard_len
; 
 471     while ((discard_len 
> 0) && len2
); 
 473     delete [] discard_buffer
; 
 478   if (_Read(&msg
, sizeof(msg
)) != sizeof(msg
)) 
 481   sig 
= (wxUint32
)msg
.sig
[0]; 
 482   sig 
|= (wxUint32
)(msg
.sig
[1] << 8); 
 483   sig 
|= (wxUint32
)(msg
.sig
[2] << 16); 
 484   sig 
|= (wxUint32
)(msg
.sig
[3] << 24); 
 486   if (sig 
!= 0xdeadfeed) 
 488     wxLogWarning(_("wxSocket: invalid signature in ReadMsg.")); 
 504 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
) 
 509   m_lcount 
= _Read(buffer
, nbytes
); 
 510   Pushback(buffer
, m_lcount
); 
 512   // If in wxSOCKET_WAITALL mode, all bytes should have been read. 
 513   if (m_flags 
& wxSOCKET_WAITALL
) 
 514     m_error 
= (m_lcount 
!= nbytes
); 
 516     m_error 
= (m_lcount 
== 0); 
 518   // Allow read events again 
 524 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
) 
 529   m_lcount 
= _Write(buffer
, nbytes
); 
 531   // If in wxSOCKET_WAITALL mode, all bytes should have been written. 
 532   if (m_flags 
& wxSOCKET_WAITALL
) 
 533     m_error 
= (m_lcount 
!= nbytes
); 
 535     m_error 
= (m_lcount 
== 0); 
 537   // Allow write events again 
 543 wxUint32 
wxSocketBase::_Write(const void *buffer_
, wxUint32 nbytes
) 
 545   const char *buffer 
= (const char *)buffer_
; 
 549   // If the socket is invalid or parameters are ill, return immediately 
 550   if (!m_socket 
|| !buffer 
|| !nbytes
) 
 553   // Possible combinations (they are checked in this order) 
 555   // wxSOCKET_WAITALL (with or without wxSOCKET_BLOCK) 
 560   if (m_flags 
& wxSOCKET_NOWAIT
) 
 562     m_socket
->SetNonBlocking(1); 
 563     ret 
= m_socket
->Write(buffer
, nbytes
); 
 564     m_socket
->SetNonBlocking(0); 
 569   else // blocking socket 
 573       if ( !(m_flags 
& wxSOCKET_BLOCK
) && !WaitForWrite() ) 
 576       ret 
= m_socket
->Write(buffer
, nbytes
); 
 578       // see comments for similar logic for ret handling in _Read() 
 591       if ( !(m_flags 
& wxSOCKET_WAITALL
) ) 
 598       buffer 
= (const char *)buffer 
+ ret
; 
 605 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
) 
 611     unsigned char sig
[4]; 
 612     unsigned char len
[4]; 
 620   SetFlags((m_flags 
& wxSOCKET_BLOCK
) | wxSOCKET_WAITALL
); 
 622   msg
.sig
[0] = (unsigned char) 0xad; 
 623   msg
.sig
[1] = (unsigned char) 0xde; 
 624   msg
.sig
[2] = (unsigned char) 0xed; 
 625   msg
.sig
[3] = (unsigned char) 0xfe; 
 627   msg
.len
[0] = (unsigned char) (nbytes 
& 0xff); 
 628   msg
.len
[1] = (unsigned char) ((nbytes 
>> 8) & 0xff); 
 629   msg
.len
[2] = (unsigned char) ((nbytes 
>> 16) & 0xff); 
 630   msg
.len
[3] = (unsigned char) ((nbytes 
>> 24) & 0xff); 
 632   if (_Write(&msg
, sizeof(msg
)) < sizeof(msg
)) 
 635   total 
= _Write(buffer
, nbytes
); 
 640   msg
.sig
[0] = (unsigned char) 0xed; 
 641   msg
.sig
[1] = (unsigned char) 0xfe; 
 642   msg
.sig
[2] = (unsigned char) 0xad; 
 643   msg
.sig
[3] = (unsigned char) 0xde; 
 644   msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0; 
 646   if ((_Write(&msg
, sizeof(msg
))) < sizeof(msg
)) 
 660 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
) 
 663     Pushback(buffer
, nbytes
); 
 671 wxSocketBase
& wxSocketBase::Discard() 
 673   char *buffer 
= new char[MAX_DISCARD_SIZE
]; 
 680   SetFlags(wxSOCKET_NOWAIT
); 
 684     ret 
= _Read(buffer
, MAX_DISCARD_SIZE
); 
 687   while (ret 
== MAX_DISCARD_SIZE
); 
 693   // Allow read events again 
 699 // -------------------------------------------------------------------------- 
 701 // -------------------------------------------------------------------------- 
 703 // All Wait functions poll the socket using GSocket_Select() to 
 704 // check for the specified combination of conditions, until one 
 705 // of these conditions become true, an error occurs, or the 
 706 // timeout elapses. The polling loop runs the event loop so that 
 707 // this won't block the GUI. 
 709 bool wxSocketBase::_Wait(long seconds
, 
 711                          wxSocketEventFlags flags
) 
 713   GSocketEventFlags result
; 
 714   long timeout
; // in ms 
 716   // Set this to true to interrupt ongoing waits 
 719   // Check for valid socket 
 723   // Check for valid timeout value. 
 725     timeout 
= seconds 
* 1000 + milliseconds
; 
 727     timeout 
= m_timeout 
* 1000; 
 729   // Get the active event loop 
 730   wxEventLoopBase 
* const eventLoop 
= wxEventLoop::GetActive(); 
 733   wxASSERT_MSG( !wxIsMainThread() || eventLoop
, 
 734                 "Sockets won't work without a running event loop" ); 
 737   // Wait in an active polling loop. 
 739   // NOTE: We duplicate some of the code in OnRequest, but this doesn't 
 740   //   hurt. It has to be here because the (GSocket) event might arrive 
 741   //   a bit delayed, and it has to be in OnRequest as well because we 
 742   //   don't know whether the Wait functions are being used. 
 744   // Do this at least once (important if timeout == 0, when 
 745   // we are just polling). Also, if just polling, do not yield. 
 747   const wxMilliClock_t time_limit 
= wxGetLocalTimeMillis() + timeout
; 
 749   bool valid_result 
= false; 
 753     // This is used to avoid a busy loop on wxBase - having a select 
 754     // timeout of 50 ms per iteration should be enough. 
 756       m_socket
->SetTimeout(50); 
 758       m_socket
->SetTimeout(timeout
); 
 763     result 
= m_socket
->Select(flags 
| GSOCK_LOST_FLAG
); 
 765     // Incoming connection (server) or connection established (client) 
 766     if (result 
& GSOCK_CONNECTION_FLAG
) 
 769       m_establishing 
= false; 
 774     // Data available or output buffer ready 
 775     if ((result 
& GSOCK_INPUT_FLAG
) || (result 
& GSOCK_OUTPUT_FLAG
)) 
 782     if (result 
& GSOCK_LOST_FLAG
) 
 785       m_establishing 
= false; 
 786       valid_result 
= ((flags 
& GSOCK_LOST_FLAG
) != 0); 
 791     long time_left 
= wxMilliClockToLong(time_limit 
- wxGetLocalTimeMillis()); 
 792     if ((!timeout
) || (time_left 
<= 0) || (m_interrupt
)) 
 798         // from the main thread itself we have to run the event loop to let the 
 799         // events (including the GUI events and the low-level (not wxWidgets) 
 800         // events from GSocket) be processed but from another thread it is 
 801         // enough to just call wxThread::Yield() which will give away the rest 
 802         // of our time slice: the explanation is that the events will be 
 803         // processed by the main thread anyhow, but we don't want to eat the 
 804         // CPU time uselessly while sitting in the loop waiting for the data 
 805         if ( wxIsMainThread() ) 
 807           if ( eventLoop
->Pending() ) 
 808               eventLoop
->Dispatch(); 
 813 #endif // wxUSE_THREADS 
 817         // If there's less than 50 ms left, just call select with that timeout. 
 819           m_socket
->SetTimeout(time_left
); 
 824   // Set timeout back to original value (we overwrote it for polling) 
 826     m_socket
->SetTimeout(m_timeout
*1000); 
 831 bool wxSocketBase::Wait(long seconds
, long milliseconds
) 
 833     return _Wait(seconds
, milliseconds
, GSOCK_INPUT_FLAG 
| 
 835                                         GSOCK_CONNECTION_FLAG 
| 
 839 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
) 
 841   // Check pushback buffer before entering _Wait 
 845   // Note that GSOCK_INPUT_LOST has to be explicitly passed to 
 846   // _Wait because of the semantics of WaitForRead: a return 
 847   // value of true means that a GSocket_Read call will return 
 848   // immediately, not that there is actually data to read. 
 850   return _Wait(seconds
, milliseconds
, GSOCK_INPUT_FLAG 
| 
 855 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
) 
 857     return _Wait(seconds
, milliseconds
, GSOCK_OUTPUT_FLAG
); 
 860 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
) 
 862     return _Wait(seconds
, milliseconds
, GSOCK_LOST_FLAG
); 
 865 // -------------------------------------------------------------------------- 
 867 // -------------------------------------------------------------------------- 
 870 // Get local or peer address 
 873 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const 
 880   peer 
= m_socket
->GetPeer(); 
 882     // copying a null address would just trigger an assert anyway 
 887   addr_man
.SetAddress(peer
); 
 888   GAddress_destroy(peer
); 
 893 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const 
 900     local 
= m_socket
->GetLocal(); 
 901     addr_man
.SetAddress(local
); 
 902     GAddress_destroy(local
); 
 908 // Save and restore socket state 
 911 void wxSocketBase::SaveState() 
 913     wxSocketState 
*state
; 
 915     state 
= new wxSocketState(); 
 917     state
->m_flags      
= m_flags
; 
 918     state
->m_notify     
= m_notify
; 
 919     state
->m_eventmask  
= m_eventmask
; 
 920     state
->m_clientData 
= m_clientData
; 
 922     m_states
.Append(state
); 
 925 void wxSocketBase::RestoreState() 
 927     wxList::compatibility_iterator node
; 
 928     wxSocketState 
*state
; 
 930     node 
= m_states
.GetLast(); 
 934     state 
= (wxSocketState 
*)node
->GetData(); 
 936     m_flags      
= state
->m_flags
; 
 937     m_notify     
= state
->m_notify
; 
 938     m_eventmask  
= state
->m_eventmask
; 
 939     m_clientData 
= state
->m_clientData
; 
 941     m_states
.Erase(node
); 
 949 void wxSocketBase::SetTimeout(long seconds
) 
 954         m_socket
->SetTimeout(m_timeout 
* 1000); 
 957 void wxSocketBase::SetFlags(wxSocketFlags flags
) 
 963 // -------------------------------------------------------------------------- 
 965 // -------------------------------------------------------------------------- 
 967 // A note on how events are processed, which is probably the most 
 968 // difficult thing to get working right while keeping the same API 
 969 // and functionality for all platforms. 
 971 // When GSocket detects an event, it calls wx_socket_callback, which in 
 972 // turn just calls wxSocketBase::OnRequest in the corresponding wxSocket 
 973 // object. OnRequest does some housekeeping, and if the event is to be 
 974 // propagated to the user, it creates a new wxSocketEvent object and 
 975 // posts it. The event is not processed immediately, but delayed with 
 976 // AddPendingEvent instead. This is necessary in order to decouple the 
 977 // event processing from wx_socket_callback; otherwise, subsequent IO 
 978 // calls made from the user event handler would fail, as gtk callbacks 
 979 // are not reentrant. 
 981 // Note that, unlike events, user callbacks (now deprecated) are _not_ 
 982 // decoupled from wx_socket_callback and thus they suffer from a variety 
 983 // of problems. Avoid them where possible and use events instead. 
 986 void LINKAGEMODE 
wx_socket_callback(GSocket 
* WXUNUSED(socket
), 
 987                                     GSocketEvent notification
, 
 990     wxSocketBase 
*sckobj 
= (wxSocketBase 
*)cdata
; 
 992     sckobj
->OnRequest((wxSocketNotify
) notification
); 
 995 void wxSocketBase::OnRequest(wxSocketNotify notification
) 
 997   // NOTE: We duplicate some of the code in _Wait, but this doesn't 
 998   //   hurt. It has to be here because the (GSocket) event might arrive 
 999   //   a bit delayed, and it has to be in _Wait as well because we don't 
1000   //   know whether the Wait functions are being used. 
1002   switch(notification
) 
1004     case wxSOCKET_CONNECTION
: 
1005       m_establishing 
= false; 
1009     // If we are in the middle of a R/W operation, do not 
1010     // propagate events to users. Also, filter 'late' events 
1011     // which are no longer valid. 
1013     case wxSOCKET_INPUT
: 
1014       if (m_reading 
|| !m_socket
->Select(GSOCK_INPUT_FLAG
)) 
1018     case wxSOCKET_OUTPUT
: 
1019       if (m_writing 
|| !m_socket
->Select(GSOCK_OUTPUT_FLAG
)) 
1024       m_connected 
= false; 
1025       m_establishing 
= false; 
1032   // Schedule the event 
1034   wxSocketEventFlags flag 
= 0; 
1036   switch (notification
) 
1038     case GSOCK_INPUT
:      flag 
= GSOCK_INPUT_FLAG
; break; 
1039     case GSOCK_OUTPUT
:     flag 
= GSOCK_OUTPUT_FLAG
; break; 
1040     case GSOCK_CONNECTION
: flag 
= GSOCK_CONNECTION_FLAG
; break; 
1041     case GSOCK_LOST
:       flag 
= GSOCK_LOST_FLAG
; break; 
1043       wxLogWarning(_("wxSocket: unknown event!.")); 
1047   if (((m_eventmask 
& flag
) == flag
) && m_notify
) 
1051       wxSocketEvent 
event(m_id
); 
1052       event
.m_event      
= notification
; 
1053       event
.m_clientData 
= m_clientData
; 
1054       event
.SetEventObject(this); 
1056       m_handler
->AddPendingEvent(event
); 
1061 void wxSocketBase::Notify(bool notify
) 
1065         m_socket
->Notify(notify
); 
1068 void wxSocketBase::SetNotify(wxSocketEventFlags flags
) 
1070     m_eventmask 
= flags
; 
1073 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
) 
1075     m_handler 
= &handler
; 
1079 // -------------------------------------------------------------------------- 
1081 // -------------------------------------------------------------------------- 
1083 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
) 
1087   if (m_unread 
== NULL
) 
1088     m_unread 
= malloc(size
); 
1093     tmp 
= malloc(m_unrd_size 
+ size
); 
1094     memcpy((char *)tmp 
+ size
, m_unread
, m_unrd_size
); 
1100   m_unrd_size 
+= size
; 
1102   memcpy(m_unread
, buffer
, size
); 
1105 wxUint32 
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
) 
1110   if (size 
> (m_unrd_size
-m_unrd_cur
)) 
1111     size 
= m_unrd_size
-m_unrd_cur
; 
1113   memcpy(buffer
, (char *)m_unread 
+ m_unrd_cur
, size
); 
1118     if (m_unrd_size 
== m_unrd_cur
) 
1131 // ========================================================================== 
1133 // ========================================================================== 
1135 // -------------------------------------------------------------------------- 
1137 // -------------------------------------------------------------------------- 
1139 wxSocketServer::wxSocketServer(const wxSockAddress
& addr_man
, 
1140                                wxSocketFlags flags
) 
1141               : wxSocketBase(flags
, wxSOCKET_SERVER
) 
1143     wxLogTrace( wxTRACE_Socket
, _T("Opening wxSocketServer") ); 
1145     m_socket 
= GSocket_new(); 
1149         wxLogTrace( wxTRACE_Socket
, _T("*** GSocket_new failed") ); 
1153     // Setup the socket as server 
1154     m_socket
->Notify(m_notify
); 
1155     m_socket
->SetLocal(addr_man
.GetAddress()); 
1157     if (GetFlags() & wxSOCKET_REUSEADDR
) { 
1158         m_socket
->SetReusable(); 
1160     if (GetFlags() & wxSOCKET_BROADCAST
) { 
1161         m_socket
->SetBroadcast(); 
1163     if (GetFlags() & wxSOCKET_NOBIND
) { 
1164         m_socket
->DontDoBind(); 
1167     if (m_socket
->SetServer() != GSOCK_NOERROR
) 
1172         wxLogTrace( wxTRACE_Socket
, _T("*** GSocket_SetServer failed") ); 
1176     m_socket
->SetTimeout(m_timeout 
* 1000); 
1177     m_socket
->SetCallback(GSOCK_INPUT_FLAG 
| GSOCK_OUTPUT_FLAG 
| 
1178                                   GSOCK_LOST_FLAG 
| GSOCK_CONNECTION_FLAG
, 
1179                                   wx_socket_callback
, (char *)this); 
1181     wxLogTrace( wxTRACE_Socket
, _T("wxSocketServer on fd %d"), m_socket
->m_fd 
); 
1184 // -------------------------------------------------------------------------- 
1186 // -------------------------------------------------------------------------- 
1188 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
) 
1190   GSocket 
*child_socket
; 
1195   // If wait == false, then the call should be nonblocking. 
1196   // When we are finished, we put the socket to blocking mode 
1200     m_socket
->SetNonBlocking(1); 
1202   child_socket 
= m_socket
->WaitConnection(); 
1205     m_socket
->SetNonBlocking(0); 
1210   sock
.m_type 
= wxSOCKET_BASE
; 
1211   sock
.m_socket 
= child_socket
; 
1212   sock
.m_connected 
= true; 
1214   sock
.m_socket
->SetTimeout(sock
.m_timeout 
* 1000); 
1215   sock
.m_socket
->SetCallback(GSOCK_INPUT_FLAG 
| GSOCK_OUTPUT_FLAG 
| 
1216                                      GSOCK_LOST_FLAG 
| GSOCK_CONNECTION_FLAG
, 
1217                                      wx_socket_callback
, (char *)&sock
); 
1222 wxSocketBase 
*wxSocketServer::Accept(bool wait
) 
1224   wxSocketBase
* sock 
= new wxSocketBase(); 
1226   sock
->SetFlags(m_flags
); 
1228   if (!AcceptWith(*sock
, wait
)) 
1237 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
) 
1239     return _Wait(seconds
, milliseconds
, GSOCK_CONNECTION_FLAG
); 
1242 bool wxSocketBase::GetOption(int level
, int optname
, void *optval
, int *optlen
) 
1244     wxASSERT_MSG( m_socket
, _T("Socket not initialised") ); 
1246     if (m_socket
->GetSockOpt(level
, optname
, optval
, optlen
) 
1254 bool wxSocketBase::SetOption(int level
, int optname
, const void *optval
, 
1257     wxASSERT_MSG( m_socket
, _T("Socket not initialised") ); 
1259     if (m_socket
->SetSockOpt(level
, optname
, optval
, optlen
) 
1267 bool wxSocketBase::SetLocal(const wxIPV4address
& local
) 
1269   GAddress
* la 
= local
.GetAddress(); 
1271   // If the address is valid, save it for use when we call Connect 
1272   if (la 
&& la
->m_addr
) 
1274     m_localAddress 
= local
; 
1282 // ========================================================================== 
1284 // ========================================================================== 
1286 // -------------------------------------------------------------------------- 
1288 // -------------------------------------------------------------------------- 
1290 wxSocketClient::wxSocketClient(wxSocketFlags flags
) 
1291               : wxSocketBase(flags
, wxSOCKET_CLIENT
) 
1293     m_initialRecvBufferSize 
= 
1294     m_initialSendBufferSize 
= -1; 
1297 wxSocketClient::~wxSocketClient() 
1301 // -------------------------------------------------------------------------- 
1303 // -------------------------------------------------------------------------- 
1305 bool wxSocketClient::DoConnect(const wxSockAddress
& addr_man
, 
1306                                const wxSockAddress
* local
, 
1313     // Shutdown and destroy the socket 
1318   m_socket 
= GSocket_new(); 
1319   m_connected 
= false; 
1320   m_establishing 
= false; 
1325   m_socket
->SetTimeout(m_timeout 
* 1000); 
1326   m_socket
->SetCallback(GSOCK_INPUT_FLAG 
| GSOCK_OUTPUT_FLAG 
| 
1327                                 GSOCK_LOST_FLAG 
| GSOCK_CONNECTION_FLAG
, 
1328                                 wx_socket_callback
, (char *)this); 
1330   // If wait == false, then the call should be nonblocking. 
1331   // When we are finished, we put the socket to blocking mode 
1335     m_socket
->SetNonBlocking(1); 
1337   // Reuse makes sense for clients too, if we are trying to rebind to the same port 
1338   if (GetFlags() & wxSOCKET_REUSEADDR
) 
1340     m_socket
->SetReusable(); 
1342   if (GetFlags() & wxSOCKET_BROADCAST
) 
1344     m_socket
->SetBroadcast(); 
1346   if (GetFlags() & wxSOCKET_NOBIND
) 
1348     m_socket
->DontDoBind(); 
1351   // If no local address was passed and one has been set, use the one that was Set 
1352   if (!local 
&& m_localAddress
.GetAddress()) 
1354     local 
= &m_localAddress
; 
1357   // Bind to the local IP address and port, when provided 
1360     GAddress
* la 
= local
->GetAddress(); 
1362     if (la 
&& la
->m_addr
) 
1363       m_socket
->SetLocal(la
); 
1366 #if defined(__WXMSW__) || defined(__WXGTK__) 
1367   m_socket
->SetInitialSocketBuffers(m_initialRecvBufferSize
, m_initialSendBufferSize
); 
1370   m_socket
->SetPeer(addr_man
.GetAddress()); 
1371   err 
= m_socket
->Connect(GSOCK_STREAMED
); 
1373   //this will register for callbacks - must be called after m_socket->m_fd was initialized 
1374   m_socket
->Notify(m_notify
); 
1377     m_socket
->SetNonBlocking(0); 
1379   if (err 
!= GSOCK_NOERROR
) 
1381     if (err 
== GSOCK_WOULDBLOCK
) 
1382       m_establishing 
= true; 
1391 bool wxSocketClient::Connect(const wxSockAddress
& addr_man
, bool wait
) 
1393     return DoConnect(addr_man
, NULL
, wait
); 
1396 bool wxSocketClient::Connect(const wxSockAddress
& addr_man
, 
1397                              const wxSockAddress
& local
, 
1400     return DoConnect(addr_man
, &local
, wait
); 
1403 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
) 
1405     if (m_connected
)                      // Already connected 
1408     if (!m_establishing 
|| !m_socket
)     // No connection in progress 
1411     return _Wait(seconds
, milliseconds
, GSOCK_CONNECTION_FLAG 
| 
1415 // ========================================================================== 
1417 // ========================================================================== 
1419 /* NOTE: experimental stuff - might change */ 
1421 wxDatagramSocket::wxDatagramSocket( const wxSockAddress
& addr
, 
1422                                     wxSocketFlags flags 
) 
1423                 : wxSocketBase( flags
, wxSOCKET_DATAGRAM 
) 
1425     // Create the socket 
1426     m_socket 
= GSocket_new(); 
1430         wxFAIL_MSG( _T("datagram socket not new'd") ); 
1433     m_socket
->Notify(m_notify
); 
1434     // Setup the socket as non connection oriented 
1435     m_socket
->SetLocal(addr
.GetAddress()); 
1436     if (flags 
& wxSOCKET_REUSEADDR
) 
1438         m_socket
->SetReusable(); 
1440     if (GetFlags() & wxSOCKET_BROADCAST
) 
1442         m_socket
->SetBroadcast(); 
1444     if (GetFlags() & wxSOCKET_NOBIND
) 
1446         m_socket
->DontDoBind(); 
1448     if ( m_socket
->SetNonOriented() != GSOCK_NOERROR 
) 
1455     // Initialize all stuff 
1456     m_connected 
= false; 
1457     m_establishing 
= false; 
1458     m_socket
->SetTimeout( m_timeout 
); 
1459     m_socket
->SetCallback( GSOCK_INPUT_FLAG 
| GSOCK_OUTPUT_FLAG 
| 
1460                            GSOCK_LOST_FLAG 
| GSOCK_CONNECTION_FLAG
, 
1461                            wx_socket_callback
, (char*)this ); 
1464 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
, 
1473 wxDatagramSocket
& wxDatagramSocket::SendTo( const wxSockAddress
& addr
, 
1477     wxASSERT_MSG( m_socket
, _T("Socket not initialised") ); 
1479     m_socket
->SetPeer(addr
.GetAddress()); 
1484 // ========================================================================== 
1486 // ========================================================================== 
1488 class wxSocketModule 
: public wxModule
 
1491     virtual bool OnInit() 
1493         // wxSocketBase will call GSocket_Init() itself when/if needed 
1497     virtual void OnExit() 
1499         if ( wxSocketBase::IsInitialized() ) 
1500             wxSocketBase::Shutdown(); 
1504     DECLARE_DYNAMIC_CLASS(wxSocketModule
) 
1507 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)