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) 1999-2000, Guillermo Rodriguez Garcia
8 // (C) 2008 Vadim Zeitlin
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
13 // ==========================================================================
15 // ==========================================================================
17 // For compilers that support precompilation, includes "wx.h".
18 #include "wx/wxprec.h"
26 #include "wx/socket.h"
29 #include "wx/object.h"
30 #include "wx/string.h"
37 #include "wx/module.h"
40 #include "wx/apptrait.h"
41 #include "wx/sckaddr.h"
42 #include "wx/stopwatch.h"
43 #include "wx/thread.h"
44 #include "wx/evtloop.h"
47 #include "wx/private/fd.h"
48 #include "wx/private/socket.h"
54 // we use MSG_NOSIGNAL to avoid getting SIGPIPE when sending data to a remote
55 // host which closed the connection if it is available, otherwise we rely on
56 // SO_NOSIGPIPE existency
58 // this should cover all the current Unix systems (Windows never sends any
59 // signals anyhow) but if we find one that has neither we should explicitly
60 // ignore SIGPIPE for it
61 // OpenVMS has neither MSG_NOSIGNAL nor SO_NOSIGPIPE. However the socket sample
62 // seems to work. Not sure if problems will show up on OpenVMS using sockets.
64 #define wxSOCKET_MSG_NOSIGNAL MSG_NOSIGNAL
65 #else // MSG_NOSIGNAL not available (BSD including OS X)
66 // next best possibility is to use SO_NOSIGPIPE socket option, this covers
67 // BSD systems (including OS X) -- but if we don't have it neither (AIX and
68 // old HP-UX do not), we have to fall back to the old way of simply
69 // disabling SIGPIPE temporarily, so define a class to do it in a safe way
70 #if defined(__UNIX__) && !defined(SO_NOSIGPIPE)
71 extern "C" { typedef void (*wxSigHandler_t
)(int); }
77 // ctor disables the given signal
79 : m_handler(signal(sig
, SIG_IGN
)),
84 // dtor restores the old handler
87 signal(m_sig
, m_handler
);
91 const wxSigHandler_t m_handler
;
94 wxDECLARE_NO_COPY_CLASS(IgnoreSignal
);
96 } // anonymous namespace
98 #define wxNEEDS_IGNORE_SIGPIPE
99 #endif // Unix without SO_NOSIGPIPE
101 #define wxSOCKET_MSG_NOSIGNAL 0
104 // DLL options compatibility check:
105 #include "wx/build.h"
106 WX_CHECK_BUILD_OPTIONS("wxNet")
108 // --------------------------------------------------------------------------
109 // macros and constants
110 // --------------------------------------------------------------------------
113 wxDEFINE_EVENT(wxEVT_SOCKET
, wxSocketEvent
);
116 #define MAX_DISCARD_SIZE (10 * 1024)
118 #define wxTRACE_Socket wxT("wxSocket")
120 // --------------------------------------------------------------------------
122 // --------------------------------------------------------------------------
124 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
125 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
126 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
127 IMPLEMENT_CLASS(wxDatagramSocket
, wxSocketBase
)
128 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
130 // ----------------------------------------------------------------------------
132 // ----------------------------------------------------------------------------
137 void SetTimeValFromMS(timeval
& tv
, unsigned long ms
)
139 tv
.tv_sec
= (ms
/ 1000);
140 tv
.tv_usec
= (ms
% 1000) * 1000;
143 } // anonymous namespace
145 // --------------------------------------------------------------------------
147 // --------------------------------------------------------------------------
149 class wxSocketState
: public wxObject
152 wxSocketFlags m_flags
;
153 wxSocketEventFlags m_eventmask
;
158 wxSocketState() : wxObject() {}
160 wxDECLARE_NO_COPY_CLASS(wxSocketState
);
163 // wxSocketWaitModeChanger: temporarily change the socket flags affecting its
165 class wxSocketWaitModeChanger
168 // temporarily set the flags to include the flag value which may be either
169 // wxSOCKET_NOWAIT or wxSOCKET_WAITALL
170 wxSocketWaitModeChanger(wxSocketBase
*socket
, int flag
)
172 m_oldflags(socket
->GetFlags())
175 wxASSERT_MSG( flag
== wxSOCKET_WAITALL
|| flag
== wxSOCKET_NOWAIT
,
178 // preserve wxSOCKET_BLOCK value when switching to wxSOCKET_WAITALL
179 // mode but not when switching to wxSOCKET_NOWAIT as the latter is
180 // incompatible with wxSOCKET_BLOCK
181 if ( flag
!= wxSOCKET_NOWAIT
)
182 flag
|= m_oldflags
& wxSOCKET_BLOCK
;
184 socket
->SetFlags(flag
);
187 ~wxSocketWaitModeChanger()
189 m_socket
->SetFlags(m_oldflags
);
193 wxSocketBase
* const m_socket
;
194 const int m_oldflags
;
196 wxDECLARE_NO_COPY_CLASS(wxSocketWaitModeChanger
);
199 // wxSocketRead/WriteGuard are instantiated before starting reading
200 // from/writing to the socket
201 class wxSocketReadGuard
204 wxSocketReadGuard(wxSocketBase
*socket
)
207 wxASSERT_MSG( !m_socket
->m_reading
, "read reentrancy?" );
209 m_socket
->m_reading
= true;
214 m_socket
->m_reading
= false;
216 // connection could have been lost while reading, in this case calling
217 // ReenableEvents() would assert and is not necessary anyhow
218 wxSocketImpl
* const impl
= m_socket
->m_impl
;
219 if ( impl
&& impl
->m_fd
!= INVALID_SOCKET
)
220 impl
->ReenableEvents(wxSOCKET_INPUT_FLAG
);
224 wxSocketBase
* const m_socket
;
226 wxDECLARE_NO_COPY_CLASS(wxSocketReadGuard
);
229 class wxSocketWriteGuard
232 wxSocketWriteGuard(wxSocketBase
*socket
)
235 wxASSERT_MSG( !m_socket
->m_writing
, "write reentrancy?" );
237 m_socket
->m_writing
= true;
240 ~wxSocketWriteGuard()
242 m_socket
->m_writing
= false;
244 wxSocketImpl
* const impl
= m_socket
->m_impl
;
245 if ( impl
&& impl
->m_fd
!= INVALID_SOCKET
)
246 impl
->ReenableEvents(wxSOCKET_OUTPUT_FLAG
);
250 wxSocketBase
* const m_socket
;
252 wxDECLARE_NO_COPY_CLASS(wxSocketWriteGuard
);
255 // ============================================================================
257 // ============================================================================
259 wxSocketManager
*wxSocketManager::ms_manager
= NULL
;
262 void wxSocketManager::Set(wxSocketManager
*manager
)
264 wxASSERT_MSG( !ms_manager
, "too late to set manager now" );
266 ms_manager
= manager
;
270 void wxSocketManager::Init()
272 wxASSERT_MSG( !ms_manager
, "shouldn't be initialized twice" );
275 Details: Initialize() creates a hidden window as a sink for socket
276 events, such as 'read completed'. wxMSW has only one message loop
277 for the main thread. If Initialize is called in a secondary thread,
278 the socket window will be created for the secondary thread, but
279 since there is no message loop on this thread, it will never
280 receive events and all socket operations will time out.
281 BTW, the main thread must not be stopped using sleep or block
282 on a semaphore (a bad idea in any case) or socket operations
285 On the Mac side, Initialize() stores a pointer to the CFRunLoop for
286 the main thread. Because secondary threads do not have run loops,
287 adding event notifications to the "Current" loop would have no
288 effect at all, events would never fire.
290 wxASSERT_MSG( wxIsMainThread(),
291 "sockets must be initialized from the main thread" );
293 wxAppConsole
* const app
= wxAppConsole::GetInstance();
294 wxCHECK_RET( app
, "sockets can't be initialized without wxApp" );
296 ms_manager
= app
->GetTraits()->GetSocketManager();
299 // ==========================================================================
301 // ==========================================================================
303 wxSocketImpl::wxSocketImpl(wxSocketBase
& wxsocket
)
304 : m_wxsocket(&wxsocket
)
306 m_fd
= INVALID_SOCKET
;
307 m_error
= wxSOCKET_NOERROR
;
311 SetTimeout(wxsocket
.GetTimeout() * 1000);
313 m_establishing
= false;
317 m_initialRecvBufferSize
= -1;
318 m_initialSendBufferSize
= -1;
321 wxSocketImpl::~wxSocketImpl()
323 if ( m_fd
!= INVALID_SOCKET
)
327 bool wxSocketImpl::PreCreateCheck(const wxSockAddressImpl
& addr
)
329 if ( m_fd
!= INVALID_SOCKET
)
331 m_error
= wxSOCKET_INVSOCK
;
337 m_error
= wxSOCKET_INVADDR
;
344 void wxSocketImpl::PostCreation()
346 // FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option
348 EnableSocketOption(SO_NOSIGPIPE
);
352 EnableSocketOption(SO_REUSEADDR
);
356 wxASSERT_MSG( !m_stream
, "broadcasting is for datagram sockets only" );
358 EnableSocketOption(SO_BROADCAST
);
361 if ( m_initialRecvBufferSize
>= 0 )
362 SetSocketOption(SO_RCVBUF
, m_initialRecvBufferSize
);
363 if ( m_initialSendBufferSize
>= 0 )
364 SetSocketOption(SO_SNDBUF
, m_initialSendBufferSize
);
366 // we always put our sockets in unblocked mode and handle blocking
367 // ourselves in DoRead/Write() if wxSOCKET_WAITALL is specified
368 UnblockAndRegisterWithEventLoop();
371 wxSocketError
wxSocketImpl::UpdateLocalAddress()
373 if ( !m_local
.IsOk() )
375 // ensure that we have a valid object using the correct family: correct
376 // being the same one as our peer uses as we have no other way to
378 m_local
.Create(m_peer
.GetFamily());
381 WX_SOCKLEN_T lenAddr
= m_local
.GetLen();
382 if ( getsockname(m_fd
, m_local
.GetWritableAddr(), &lenAddr
) != 0 )
385 m_error
= wxSOCKET_IOERR
;
389 return wxSOCKET_NOERROR
;
392 wxSocketError
wxSocketImpl::CreateServer()
394 if ( !PreCreateCheck(m_local
) )
400 // do create the socket
401 m_fd
= socket(m_local
.GetFamily(), SOCK_STREAM
, 0);
403 if ( m_fd
== INVALID_SOCKET
)
405 m_error
= wxSOCKET_IOERR
;
406 return wxSOCKET_IOERR
;
411 // and then bind to and listen on it
413 // FIXME: should we test for m_dobind here?
414 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
415 m_error
= wxSOCKET_IOERR
;
419 if ( listen(m_fd
, 5) != 0 )
420 m_error
= wxSOCKET_IOERR
;
429 // finally retrieve the address we effectively bound to
430 return UpdateLocalAddress();
433 wxSocketError
wxSocketImpl::CreateClient(bool wait
)
435 if ( !PreCreateCheck(m_peer
) )
438 m_fd
= socket(m_peer
.GetFamily(), SOCK_STREAM
, 0);
440 if ( m_fd
== INVALID_SOCKET
)
442 m_error
= wxSOCKET_IOERR
;
443 return wxSOCKET_IOERR
;
448 // If a local address has been set, then bind to it before calling connect
449 if ( m_local
.IsOk() )
451 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
454 m_error
= wxSOCKET_IOERR
;
460 int rc
= connect(m_fd
, m_peer
.GetAddr(), m_peer
.GetLen());
461 if ( rc
== SOCKET_ERROR
)
463 wxSocketError err
= GetLastError();
464 if ( err
== wxSOCKET_WOULDBLOCK
)
466 m_establishing
= true;
468 // block waiting for connection if we should (otherwise just return
469 // wxSOCKET_WOULDBLOCK to the caller)
472 err
= SelectWithTimeout(wxSOCKET_CONNECTION_FLAG
)
475 m_establishing
= false;
483 m_error
= wxSOCKET_NOERROR
;
490 wxSocketError
wxSocketImpl::CreateUDP()
492 if ( !PreCreateCheck(m_local
) )
498 m_fd
= socket(m_local
.GetFamily(), SOCK_DGRAM
, 0);
500 if ( m_fd
== INVALID_SOCKET
)
502 m_error
= wxSOCKET_IOERR
;
503 return wxSOCKET_IOERR
;
510 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
513 m_error
= wxSOCKET_IOERR
;
517 return UpdateLocalAddress();
520 return wxSOCKET_NOERROR
;
523 wxSocketImpl
*wxSocketImpl::Accept(wxSocketBase
& wxsocket
)
525 wxSockAddressStorage from
;
526 WX_SOCKLEN_T fromlen
= sizeof(from
);
527 const SOCKET fd
= accept(m_fd
, &from
.addr
, &fromlen
);
529 // accepting is similar to reading in the sense that it resets "ready for
530 // read" flag on the socket
531 ReenableEvents(wxSOCKET_INPUT_FLAG
);
533 if ( fd
== INVALID_SOCKET
)
536 wxSocketManager
* const manager
= wxSocketManager::Get();
540 wxSocketImpl
* const sock
= manager
->CreateSocket(wxsocket
);
545 sock
->m_peer
= wxSockAddressImpl(from
.addr
, fromlen
);
547 sock
->UnblockAndRegisterWithEventLoop();
553 void wxSocketImpl::Close()
555 if ( m_fd
!= INVALID_SOCKET
)
558 m_fd
= INVALID_SOCKET
;
562 void wxSocketImpl::Shutdown()
564 if ( m_fd
!= INVALID_SOCKET
)
566 shutdown(m_fd
, 1 /* SD_SEND */);
572 * Sets the timeout for blocking calls. Time is expressed in
575 void wxSocketImpl::SetTimeout(unsigned long millis
)
577 SetTimeValFromMS(m_timeout
, millis
);
580 void wxSocketImpl::NotifyOnStateChange(wxSocketNotify event
)
582 m_wxsocket
->OnRequest(event
);
585 /* Address handling */
586 wxSocketError
wxSocketImpl::SetLocal(const wxSockAddressImpl
& local
)
588 /* the socket must be initialized, or it must be a server */
589 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
591 m_error
= wxSOCKET_INVSOCK
;
592 return wxSOCKET_INVSOCK
;
597 m_error
= wxSOCKET_INVADDR
;
598 return wxSOCKET_INVADDR
;
603 return wxSOCKET_NOERROR
;
606 wxSocketError
wxSocketImpl::SetPeer(const wxSockAddressImpl
& peer
)
610 m_error
= wxSOCKET_INVADDR
;
611 return wxSOCKET_INVADDR
;
616 return wxSOCKET_NOERROR
;
619 const wxSockAddressImpl
& wxSocketImpl::GetLocal()
621 if ( !m_local
.IsOk() )
622 UpdateLocalAddress();
627 // ----------------------------------------------------------------------------
629 // ----------------------------------------------------------------------------
631 // this macro wraps the given expression (normally a syscall) in a loop which
632 // ignores any interruptions, i.e. reevaluates it again if it failed and errno
635 #define DO_WHILE_EINTR( rc, syscall ) \
639 while ( rc == -1 && errno == EINTR )
641 #define DO_WHILE_EINTR( rc, syscall ) rc = (syscall)
644 int wxSocketImpl::RecvStream(void *buffer
, int size
)
647 DO_WHILE_EINTR( ret
, recv(m_fd
, static_cast<char *>(buffer
), size
, 0) );
651 // receiving 0 bytes for a TCP socket indicates that the connection was
652 // closed by peer so shut down our end as well (for UDP sockets empty
653 // datagrams are also possible)
654 m_establishing
= false;
655 NotifyOnStateChange(wxSOCKET_LOST
);
659 // do not return an error in this case however
665 int wxSocketImpl::SendStream(const void *buffer
, int size
)
667 #ifdef wxNEEDS_IGNORE_SIGPIPE
668 IgnoreSignal
ignore(SIGPIPE
);
672 DO_WHILE_EINTR( ret
, send(m_fd
, static_cast<const char *>(buffer
), size
,
673 wxSOCKET_MSG_NOSIGNAL
) );
678 int wxSocketImpl::RecvDgram(void *buffer
, int size
)
680 wxSockAddressStorage from
;
681 WX_SOCKLEN_T fromlen
= sizeof(from
);
684 DO_WHILE_EINTR( ret
, recvfrom(m_fd
, static_cast<char *>(buffer
), size
,
685 0, &from
.addr
, &fromlen
) );
687 if ( ret
== SOCKET_ERROR
)
690 m_peer
= wxSockAddressImpl(from
.addr
, fromlen
);
691 if ( !m_peer
.IsOk() )
697 int wxSocketImpl::SendDgram(const void *buffer
, int size
)
699 if ( !m_peer
.IsOk() )
701 m_error
= wxSOCKET_INVADDR
;
706 DO_WHILE_EINTR( ret
, sendto(m_fd
, static_cast<const char *>(buffer
), size
,
707 0, m_peer
.GetAddr(), m_peer
.GetLen()) );
712 int wxSocketImpl::Read(void *buffer
, int size
)
714 // server sockets can't be used for IO, only to accept new connections
715 if ( m_fd
== INVALID_SOCKET
|| m_server
)
717 m_error
= wxSOCKET_INVSOCK
;
721 int ret
= m_stream
? RecvStream(buffer
, size
)
722 : RecvDgram(buffer
, size
);
724 m_error
= ret
== SOCKET_ERROR
? GetLastError() : wxSOCKET_NOERROR
;
729 int wxSocketImpl::Write(const void *buffer
, int size
)
731 if ( m_fd
== INVALID_SOCKET
|| m_server
)
733 m_error
= wxSOCKET_INVSOCK
;
737 int ret
= m_stream
? SendStream(buffer
, size
)
738 : SendDgram(buffer
, size
);
740 m_error
= ret
== SOCKET_ERROR
? GetLastError() : wxSOCKET_NOERROR
;
745 // ==========================================================================
747 // ==========================================================================
749 // --------------------------------------------------------------------------
750 // Initialization and shutdown
751 // --------------------------------------------------------------------------
756 // counts the number of calls to Initialize() minus the number of calls to
757 // Shutdown(): we don't really need it any more but it was documented that
758 // Shutdown() must be called the same number of times as Initialize() and using
759 // a counter helps us to check it
760 int gs_socketInitCount
= 0;
762 } // anonymous namespace
764 bool wxSocketBase::IsInitialized()
766 wxASSERT_MSG( wxIsMainThread(), "unsafe to call from other threads" );
768 return gs_socketInitCount
!= 0;
771 bool wxSocketBase::Initialize()
773 wxCHECK_MSG( wxIsMainThread(), false,
774 "must be called from the main thread" );
776 if ( !gs_socketInitCount
)
778 wxSocketManager
* const manager
= wxSocketManager::Get();
779 if ( !manager
|| !manager
->OnInit() )
783 gs_socketInitCount
++;
788 void wxSocketBase::Shutdown()
790 wxCHECK_RET( wxIsMainThread(), "must be called from the main thread" );
792 wxCHECK_RET( gs_socketInitCount
> 0, "too many calls to Shutdown()" );
794 if ( !--gs_socketInitCount
)
796 wxSocketManager
* const manager
= wxSocketManager::Get();
797 wxCHECK_RET( manager
, "should have a socket manager" );
803 // --------------------------------------------------------------------------
805 // --------------------------------------------------------------------------
807 void wxSocketBase::Init()
810 m_type
= wxSOCKET_UNINIT
;
821 m_beingDeleted
= false;
836 // when we create the first socket in the main thread we initialize the
837 // OS-dependent socket stuff: notice that this means that the user code
838 // needs to call wxSocket::Initialize() itself if the first socket it
839 // creates is not created in the main thread
840 if ( wxIsMainThread() )
844 wxLogError(_("Cannot initialize sockets"));
849 wxSocketBase::wxSocketBase()
854 wxSocketBase::wxSocketBase(wxSocketFlags flags
, wxSocketType type
)
863 wxSocketBase::~wxSocketBase()
865 // Shutdown and close the socket
869 // Destroy the implementation object
872 // Free the pushback buffer
876 bool wxSocketBase::Destroy()
878 // Delayed destruction: the socket will be deleted during the next idle
879 // loop iteration. This ensures that all pending events have been
881 m_beingDeleted
= true;
883 // Shutdown and close the socket
886 // Suppress events from now on
889 // Schedule this object for deletion instead of destroying it right now if
890 // possible as we may have other events pending for it
893 wxTheApp
->ScheduleForDestruction(this);
897 // in wxBase we might have no app object at all, don't leak memory
904 // ----------------------------------------------------------------------------
906 // ----------------------------------------------------------------------------
908 void wxSocketBase::SetError(wxSocketError error
)
910 m_impl
->m_error
= error
;
913 wxSocketError
wxSocketBase::LastError() const
915 return m_impl
->GetError();
918 // --------------------------------------------------------------------------
920 // --------------------------------------------------------------------------
922 // The following IO operations update m_lcount:
923 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
924 bool wxSocketBase::Close()
926 // Interrupt pending waits
932 m_establishing
= false;
936 void wxSocketBase::ShutdownOutput()
942 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
)
944 wxSocketReadGuard
read(this);
946 m_lcount
= DoRead(buffer
, nbytes
);
951 wxUint32
wxSocketBase::DoRead(void* buffer_
, wxUint32 nbytes
)
953 wxCHECK_MSG( m_impl
, 0, "socket must be valid" );
955 // We use pointer arithmetic here which doesn't work with void pointers.
956 char *buffer
= static_cast<char *>(buffer_
);
957 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
959 // Try the push back buffer first, even before checking whether the socket
960 // is valid to allow reading previously pushed back data from an already
962 wxUint32 total
= GetPushback(buffer
, nbytes
, false);
968 // our socket is non-blocking so Read() will return immediately if
969 // there is nothing to read yet and it's more efficient to try it first
970 // before entering DoWait() which is going to start dispatching GUI
971 // events and, even more importantly, we must do this under Windows
972 // where we're not going to get notifications about socket being ready
973 // for reading before we read all the existing data from it
974 const int ret
= !m_impl
->m_stream
|| m_connected
975 ? m_impl
->Read(buffer
, nbytes
)
979 if ( m_impl
->GetLastError() == wxSOCKET_WOULDBLOCK
)
981 // if we don't want to wait, just return immediately
982 if ( m_flags
& wxSOCKET_NOWAIT
)
984 // this shouldn't be counted as an error in this case
985 SetError(wxSOCKET_NOERROR
);
989 // otherwise wait until the socket becomes ready for reading or
990 // an error occurs on it
991 if ( !DoWaitWithTimeout(wxSOCKET_INPUT_FLAG
) )
993 // and exit if the timeout elapsed before it did
994 SetError(wxSOCKET_TIMEDOUT
);
1001 else // "real" error
1003 SetError(wxSOCKET_IOERR
);
1007 else if ( ret
== 0 )
1009 // for connection-oriented (e.g. TCP) sockets we can only read
1010 // 0 bytes if the other end has been closed, and for connectionless
1011 // ones (UDP) this flag doesn't make sense anyhow so we can set it
1012 // to true too without doing any harm
1015 // we're not going to read anything else and so if we haven't read
1016 // anything (or not everything in wxSOCKET_WAITALL case) already,
1018 if ( (m_flags
& wxSOCKET_WAITALL
) || !total
)
1019 SetError(wxSOCKET_IOERR
);
1025 // if we are happy to read something and not the entire nbytes bytes,
1027 if ( !(m_flags
& wxSOCKET_WAITALL
) )
1037 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
)
1041 unsigned char sig
[4];
1042 unsigned char len
[4];
1045 wxSocketReadGuard
read(this);
1047 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_WAITALL
);
1050 if ( DoRead(&msg
, sizeof(msg
)) == sizeof(msg
) )
1052 wxUint32 sig
= (wxUint32
)msg
.sig
[0];
1053 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
1054 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
1055 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
1057 if ( sig
== 0xfeeddead )
1059 wxUint32 len
= (wxUint32
)msg
.len
[0];
1060 len
|= (wxUint32
)(msg
.len
[1] << 8);
1061 len
|= (wxUint32
)(msg
.len
[2] << 16);
1062 len
|= (wxUint32
)(msg
.len
[3] << 24);
1067 len2
= len
- nbytes
;
1073 // Don't attempt to read if the msg was zero bytes long.
1074 m_lcount
= len
? DoRead(buffer
, len
) : 0;
1078 char discard_buffer
[MAX_DISCARD_SIZE
];
1081 // NOTE: discarded bytes don't add to m_lcount.
1084 discard_len
= len2
> MAX_DISCARD_SIZE
1087 discard_len
= DoRead(discard_buffer
, (wxUint32
)discard_len
);
1088 len2
-= (wxUint32
)discard_len
;
1090 while ((discard_len
> 0) && len2
);
1093 if ( !len2
&& DoRead(&msg
, sizeof(msg
)) == sizeof(msg
) )
1095 sig
= (wxUint32
)msg
.sig
[0];
1096 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
1097 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
1098 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
1100 if ( sig
== 0xdeadfeed )
1107 SetError(wxSOCKET_IOERR
);
1112 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
)
1114 wxSocketReadGuard
read(this);
1116 // Peek() should never block
1117 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_NOWAIT
);
1119 m_lcount
= DoRead(buffer
, nbytes
);
1121 Pushback(buffer
, m_lcount
);
1126 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
)
1128 wxSocketWriteGuard
write(this);
1130 m_lcount
= DoWrite(buffer
, nbytes
);
1135 // This function is a mirror image of DoRead() except that it doesn't use the
1136 // push back buffer and doesn't treat 0 return value specially (normally this
1137 // shouldn't happen at all here), so please see comments there for explanations
1138 wxUint32
wxSocketBase::DoWrite(const void *buffer_
, wxUint32 nbytes
)
1140 wxCHECK_MSG( m_impl
, 0, "socket must be valid" );
1142 const char *buffer
= static_cast<const char *>(buffer_
);
1143 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1148 if ( m_impl
->m_stream
&& !m_connected
)
1150 if ( (m_flags
& wxSOCKET_WAITALL
) || !total
)
1151 SetError(wxSOCKET_IOERR
);
1155 const int ret
= m_impl
->Write(buffer
, nbytes
);
1158 if ( m_impl
->GetLastError() == wxSOCKET_WOULDBLOCK
)
1160 if ( m_flags
& wxSOCKET_NOWAIT
)
1163 if ( !DoWaitWithTimeout(wxSOCKET_OUTPUT_FLAG
) )
1165 SetError(wxSOCKET_TIMEDOUT
);
1171 else // "real" error
1173 SetError(wxSOCKET_IOERR
);
1180 if ( !(m_flags
& wxSOCKET_WAITALL
) )
1190 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
)
1194 unsigned char sig
[4];
1195 unsigned char len
[4];
1198 wxSocketWriteGuard
write(this);
1200 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_WAITALL
);
1202 msg
.sig
[0] = (unsigned char) 0xad;
1203 msg
.sig
[1] = (unsigned char) 0xde;
1204 msg
.sig
[2] = (unsigned char) 0xed;
1205 msg
.sig
[3] = (unsigned char) 0xfe;
1207 msg
.len
[0] = (unsigned char) (nbytes
& 0xff);
1208 msg
.len
[1] = (unsigned char) ((nbytes
>> 8) & 0xff);
1209 msg
.len
[2] = (unsigned char) ((nbytes
>> 16) & 0xff);
1210 msg
.len
[3] = (unsigned char) ((nbytes
>> 24) & 0xff);
1213 if ( DoWrite(&msg
, sizeof(msg
)) == sizeof(msg
) )
1215 m_lcount
= DoWrite(buffer
, nbytes
);
1216 if ( m_lcount
== nbytes
)
1218 msg
.sig
[0] = (unsigned char) 0xed;
1219 msg
.sig
[1] = (unsigned char) 0xfe;
1220 msg
.sig
[2] = (unsigned char) 0xad;
1221 msg
.sig
[3] = (unsigned char) 0xde;
1225 msg
.len
[3] = (char) 0;
1227 if ( DoWrite(&msg
, sizeof(msg
)) == sizeof(msg
))
1233 SetError(wxSOCKET_IOERR
);
1238 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
)
1241 Pushback(buffer
, nbytes
);
1243 SetError(wxSOCKET_NOERROR
);
1249 wxSocketBase
& wxSocketBase::Discard()
1251 char *buffer
= new char[MAX_DISCARD_SIZE
];
1255 wxSocketReadGuard
read(this);
1257 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_NOWAIT
);
1261 ret
= DoRead(buffer
, MAX_DISCARD_SIZE
);
1264 while (ret
== MAX_DISCARD_SIZE
);
1268 SetError(wxSOCKET_NOERROR
);
1273 // --------------------------------------------------------------------------
1275 // --------------------------------------------------------------------------
1278 This function will check for the events specified in the flags parameter,
1279 and it will return a mask indicating which operations can be performed.
1281 wxSocketEventFlags
wxSocketImpl::Select(wxSocketEventFlags flags
,
1282 const timeval
*timeout
)
1284 if ( m_fd
== INVALID_SOCKET
)
1285 return (wxSOCKET_LOST_FLAG
& flags
);
1291 tv
.tv_sec
= tv
.tv_usec
= 0;
1293 // prepare the FD sets, passing NULL for the one(s) we don't use
1295 readfds
, *preadfds
= NULL
,
1296 writefds
, *pwritefds
= NULL
,
1297 exceptfds
; // always want to know about errors
1299 if ( flags
& wxSOCKET_INPUT_FLAG
)
1301 preadfds
= &readfds
;
1302 wxFD_ZERO(preadfds
);
1303 wxFD_SET(m_fd
, preadfds
);
1306 // when using non-blocking connect() the socket becomes connected
1307 // (successfully or not) when it becomes writable
1308 if ( flags
& (wxSOCKET_OUTPUT_FLAG
| wxSOCKET_CONNECTION_FLAG
) )
1310 pwritefds
= &writefds
;
1311 wxFD_ZERO(pwritefds
);
1312 wxFD_SET(m_fd
, pwritefds
);
1315 wxFD_ZERO(&exceptfds
);
1316 wxFD_SET(m_fd
, &exceptfds
);
1318 const int rc
= select(m_fd
+ 1, preadfds
, pwritefds
, &exceptfds
, &tv
);
1320 // check for errors first
1321 if ( rc
== -1 || wxFD_ISSET(m_fd
, &exceptfds
) )
1323 m_establishing
= false;
1325 return wxSOCKET_LOST_FLAG
& flags
;
1331 wxASSERT_MSG( rc
== 1, "unexpected select() return value" );
1333 wxSocketEventFlags detected
= 0;
1334 if ( preadfds
&& wxFD_ISSET(m_fd
, preadfds
) )
1335 detected
|= wxSOCKET_INPUT_FLAG
;
1337 if ( pwritefds
&& wxFD_ISSET(m_fd
, pwritefds
) )
1339 // check for the case of non-blocking connect()
1340 if ( m_establishing
&& !m_server
)
1343 SOCKOPTLEN_T len
= sizeof(error
);
1344 m_establishing
= false;
1345 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1348 detected
= wxSOCKET_LOST_FLAG
;
1350 detected
|= wxSOCKET_CONNECTION_FLAG
;
1352 else // not called to get non-blocking connect() status
1354 detected
|= wxSOCKET_OUTPUT_FLAG
;
1358 return detected
& flags
;
1362 wxSocketBase::DoWait(long seconds
, long milliseconds
, wxSocketEventFlags flags
)
1364 // Use either the provided timeout or the default timeout value associated
1365 // with this socket.
1367 // TODO: allow waiting forever, see #9443
1368 const long timeout
= seconds
== -1 ? m_timeout
* 1000
1369 : seconds
* 1000 + milliseconds
;
1371 return DoWait(timeout
, flags
);
1375 wxSocketBase::DoWait(long timeout
, wxSocketEventFlags flags
)
1377 wxCHECK_MSG( m_impl
, -1, "can't wait on invalid socket" );
1379 // we're never going to become ready in a TCP client if we're not connected
1380 // any more (OTOH a server can call this to precisely wait for a connection
1381 // so do wait for it in this case and UDP client is never "connected")
1382 if ( !m_impl
->IsServer() &&
1383 m_impl
->m_stream
&& !m_connected
&& !m_establishing
)
1386 // This can be set to true from Interrupt() to exit this function a.s.a.p.
1387 m_interrupt
= false;
1390 const wxMilliClock_t timeEnd
= wxGetLocalTimeMillis() + timeout
;
1392 // Get the active event loop which we'll use for the message dispatching
1393 // when running in the main thread unless this was explicitly disabled by
1394 // setting wxSOCKET_BLOCK flag
1395 wxEventLoopBase
*eventLoop
;
1396 if ( !(m_flags
& wxSOCKET_BLOCK
) && wxIsMainThread() )
1398 eventLoop
= wxEventLoop::GetActive();
1400 else // in worker thread
1402 // We never dispatch messages from threads other than the main one.
1406 // Make sure the events we're interested in are enabled before waiting for
1407 // them: this is really necessary here as otherwise this could happen:
1408 // 1. DoRead(wxSOCKET_WAITALL) is called
1409 // 2. There is nothing to read so DoWait(wxSOCKET_INPUT_FLAG) is called
1410 // 3. Some, but not all data appears, wxSocketImplUnix::OnReadWaiting()
1411 // is called and wxSOCKET_INPUT_FLAG events are disabled in it
1412 // 4. Because of wxSOCKET_WAITALL we call DoWait() again but the events
1413 // are still disabled and we block forever
1415 // More elegant solution would be nice but for now simply re-enabling the
1416 // events here will do
1417 m_impl
->ReenableEvents(flags
& (wxSOCKET_INPUT_FLAG
| wxSOCKET_OUTPUT_FLAG
));
1420 // Wait until we receive the event we're waiting for or the timeout expires
1421 // (but note that we always execute the loop at least once, even if timeout
1422 // is 0 as this is used for polling)
1424 for ( bool firstTime
= true; !m_interrupt
; firstTime
= false )
1426 long timeLeft
= wxMilliClockToLong(timeEnd
- wxGetLocalTimeMillis());
1435 wxSocketEventFlags events
;
1438 // reset them before starting to wait
1441 eventLoop
->DispatchTimeout(timeLeft
);
1443 events
= m_eventsgot
;
1445 else // no event loop or waiting in another thread
1447 // as explained below, we should always check for wxSOCKET_LOST_FLAG
1449 SetTimeValFromMS(tv
, timeLeft
);
1450 events
= m_impl
->Select(flags
| wxSOCKET_LOST_FLAG
, &tv
);
1453 // always check for wxSOCKET_LOST_FLAG, even if flags doesn't include
1454 // it, as continuing to wait for anything else after getting it is
1456 if ( events
& wxSOCKET_LOST_FLAG
)
1458 m_connected
= false;
1459 m_establishing
= false;
1464 // otherwise mask out the bits we're not interested in
1467 // Incoming connection (server) or connection established (client)?
1468 if ( events
& wxSOCKET_CONNECTION_FLAG
)
1471 m_establishing
= false;
1476 // Data available or output buffer ready?
1477 if ( (events
& wxSOCKET_INPUT_FLAG
) || (events
& wxSOCKET_OUTPUT_FLAG
) )
1487 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
1489 return DoWait(seconds
, milliseconds
,
1490 wxSOCKET_INPUT_FLAG
|
1491 wxSOCKET_OUTPUT_FLAG
|
1492 wxSOCKET_CONNECTION_FLAG
) != 0;
1495 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
1497 // Check pushback buffer before entering DoWait
1501 // Check if the socket is not already ready for input, if it is, there is
1502 // no need to start waiting for it (worse, we'll actually never get a
1503 // notification about the socket becoming ready if it is already under
1505 if ( m_impl
->Select(wxSOCKET_INPUT_FLAG
) )
1508 return DoWait(seconds
, milliseconds
, wxSOCKET_INPUT_FLAG
) != 0;
1512 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
1514 if ( m_impl
->Select(wxSOCKET_OUTPUT_FLAG
) )
1517 return DoWait(seconds
, milliseconds
, wxSOCKET_OUTPUT_FLAG
) != 0;
1520 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
1522 return DoWait(seconds
, milliseconds
, wxSOCKET_LOST_FLAG
) == -1;
1525 // --------------------------------------------------------------------------
1527 // --------------------------------------------------------------------------
1530 // Get local or peer address
1533 bool wxSocketBase::GetPeer(wxSockAddress
& addr
) const
1535 wxCHECK_MSG( m_impl
, false, "invalid socket" );
1537 const wxSockAddressImpl
& peer
= m_impl
->GetPeer();
1541 addr
.SetAddress(peer
);
1546 bool wxSocketBase::GetLocal(wxSockAddress
& addr
) const
1548 wxCHECK_MSG( m_impl
, false, "invalid socket" );
1550 const wxSockAddressImpl
& local
= m_impl
->GetLocal();
1551 if ( !local
.IsOk() )
1554 addr
.SetAddress(local
);
1560 // Save and restore socket state
1563 void wxSocketBase::SaveState()
1565 wxSocketState
*state
;
1567 state
= new wxSocketState();
1569 state
->m_flags
= m_flags
;
1570 state
->m_notify
= m_notify
;
1571 state
->m_eventmask
= m_eventmask
;
1572 state
->m_clientData
= m_clientData
;
1574 m_states
.Append(state
);
1577 void wxSocketBase::RestoreState()
1579 wxList::compatibility_iterator node
;
1580 wxSocketState
*state
;
1582 node
= m_states
.GetLast();
1586 state
= (wxSocketState
*)node
->GetData();
1588 m_flags
= state
->m_flags
;
1589 m_notify
= state
->m_notify
;
1590 m_eventmask
= state
->m_eventmask
;
1591 m_clientData
= state
->m_clientData
;
1593 m_states
.Erase(node
);
1598 // Timeout and flags
1601 void wxSocketBase::SetTimeout(long seconds
)
1603 m_timeout
= seconds
;
1606 m_impl
->SetTimeout(m_timeout
* 1000);
1609 void wxSocketBase::SetFlags(wxSocketFlags flags
)
1611 // Do some sanity checking on the flags used: not all values can be used
1613 wxASSERT_MSG( !(flags
& wxSOCKET_NOWAIT
) ||
1614 !(flags
& (wxSOCKET_WAITALL
| wxSOCKET_BLOCK
)),
1615 "Using wxSOCKET_WAITALL or wxSOCKET_BLOCK with "
1616 "wxSOCKET_NOWAIT doesn't make sense" );
1622 // --------------------------------------------------------------------------
1624 // --------------------------------------------------------------------------
1626 void wxSocketBase::OnRequest(wxSocketNotify notification
)
1628 wxSocketEventFlags flag
= 0;
1629 switch ( notification
)
1631 case wxSOCKET_INPUT
:
1632 flag
= wxSOCKET_INPUT_FLAG
;
1635 case wxSOCKET_OUTPUT
:
1636 flag
= wxSOCKET_OUTPUT_FLAG
;
1639 case wxSOCKET_CONNECTION
:
1640 flag
= wxSOCKET_CONNECTION_FLAG
;
1642 // we're now successfully connected
1644 m_establishing
= false;
1646 // error was previously set to wxSOCKET_WOULDBLOCK, but this is not
1647 // the case any longer
1648 SetError(wxSOCKET_NOERROR
);
1652 flag
= wxSOCKET_LOST_FLAG
;
1654 // if we lost the connection the socket is now closed and not
1655 // connected any more
1656 m_connected
= false;
1661 wxFAIL_MSG( "unknown wxSocket notification" );
1664 // remember the events which were generated for this socket, we're going to
1665 // use this in DoWait()
1666 m_eventsgot
|= flag
;
1668 // send the wx event if enabled and we're interested in it
1669 if ( m_notify
&& (m_eventmask
& flag
) && m_handler
)
1671 // don't generate the events when we're inside DoWait() called from our
1672 // own code as we are going to consume the data that has just become
1673 // available ourselves and the user code won't see it at all
1674 if ( (notification
== wxSOCKET_INPUT
&& m_reading
) ||
1675 (notification
== wxSOCKET_OUTPUT
&& m_writing
) )
1680 wxSocketEvent
event(m_id
);
1681 event
.m_event
= notification
;
1682 event
.m_clientData
= m_clientData
;
1683 event
.SetEventObject(this);
1685 m_handler
->AddPendingEvent(event
);
1689 void wxSocketBase::Notify(bool notify
)
1694 void wxSocketBase::SetNotify(wxSocketEventFlags flags
)
1696 m_eventmask
= flags
;
1699 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
)
1701 m_handler
= &handler
;
1705 // --------------------------------------------------------------------------
1707 // --------------------------------------------------------------------------
1709 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
)
1713 if (m_unread
== NULL
)
1714 m_unread
= malloc(size
);
1719 tmp
= malloc(m_unrd_size
+ size
);
1720 memcpy((char *)tmp
+ size
, m_unread
, m_unrd_size
);
1726 m_unrd_size
+= size
;
1728 memcpy(m_unread
, buffer
, size
);
1731 wxUint32
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
)
1733 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1738 if (size
> (m_unrd_size
-m_unrd_cur
))
1739 size
= m_unrd_size
-m_unrd_cur
;
1741 memcpy(buffer
, (char *)m_unread
+ m_unrd_cur
, size
);
1746 if (m_unrd_size
== m_unrd_cur
)
1759 // ==========================================================================
1761 // ==========================================================================
1763 // --------------------------------------------------------------------------
1765 // --------------------------------------------------------------------------
1767 wxSocketServer::wxSocketServer(const wxSockAddress
& addr
,
1768 wxSocketFlags flags
)
1769 : wxSocketBase(flags
, wxSOCKET_SERVER
)
1771 wxLogTrace( wxTRACE_Socket
, wxT("Opening wxSocketServer") );
1773 wxSocketManager
* const manager
= wxSocketManager::Get();
1774 m_impl
= manager
? manager
->CreateSocket(*this) : NULL
;
1778 wxLogTrace( wxTRACE_Socket
, wxT("*** Failed to create m_impl") );
1782 // Setup the socket as server
1783 m_impl
->SetLocal(addr
.GetAddress());
1785 if (GetFlags() & wxSOCKET_REUSEADDR
) {
1786 m_impl
->SetReusable();
1788 if (GetFlags() & wxSOCKET_BROADCAST
) {
1789 m_impl
->SetBroadcast();
1791 if (GetFlags() & wxSOCKET_NOBIND
) {
1792 m_impl
->DontDoBind();
1795 if (m_impl
->CreateServer() != wxSOCKET_NOERROR
)
1799 wxLogTrace( wxTRACE_Socket
, wxT("*** CreateServer() failed") );
1803 wxLogTrace( wxTRACE_Socket
, wxT("wxSocketServer on fd %d"), m_impl
->m_fd
);
1806 // --------------------------------------------------------------------------
1808 // --------------------------------------------------------------------------
1810 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
)
1812 if ( !m_impl
|| (m_impl
->m_fd
== INVALID_SOCKET
) || !m_impl
->IsServer() )
1814 wxFAIL_MSG( "can only be called for a valid server socket" );
1816 SetError(wxSOCKET_INVSOCK
);
1823 // wait until we get a connection
1824 if ( !m_impl
->SelectWithTimeout(wxSOCKET_INPUT_FLAG
) )
1826 SetError(wxSOCKET_TIMEDOUT
);
1832 sock
.m_impl
= m_impl
->Accept(sock
);
1836 SetError(m_impl
->GetLastError());
1841 sock
.m_type
= wxSOCKET_BASE
;
1842 sock
.m_connected
= true;
1847 wxSocketBase
*wxSocketServer::Accept(bool wait
)
1849 wxSocketBase
* sock
= new wxSocketBase();
1851 sock
->SetFlags(m_flags
);
1853 if (!AcceptWith(*sock
, wait
))
1862 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
)
1864 return DoWait(seconds
, milliseconds
, wxSOCKET_CONNECTION_FLAG
) == 1;
1867 bool wxSocketBase::GetOption(int level
, int optname
, void *optval
, int *optlen
)
1869 wxASSERT_MSG( m_impl
, wxT("Socket not initialised") );
1871 SOCKOPTLEN_T lenreal
= *optlen
;
1872 if ( getsockopt(m_impl
->m_fd
, level
, optname
,
1873 static_cast<char *>(optval
), &lenreal
) != 0 )
1882 wxSocketBase::SetOption(int level
, int optname
, const void *optval
, int optlen
)
1884 wxASSERT_MSG( m_impl
, wxT("Socket not initialised") );
1886 return setsockopt(m_impl
->m_fd
, level
, optname
,
1887 static_cast<const char *>(optval
), optlen
) == 0;
1890 bool wxSocketBase::SetLocal(const wxIPV4address
& local
)
1892 m_localAddress
= local
;
1897 // ==========================================================================
1899 // ==========================================================================
1901 // --------------------------------------------------------------------------
1903 // --------------------------------------------------------------------------
1905 wxSocketClient::wxSocketClient(wxSocketFlags flags
)
1906 : wxSocketBase(flags
, wxSOCKET_CLIENT
)
1908 m_initialRecvBufferSize
=
1909 m_initialSendBufferSize
= -1;
1912 // --------------------------------------------------------------------------
1914 // --------------------------------------------------------------------------
1916 bool wxSocketClient::DoConnect(const wxSockAddress
& remote
,
1917 const wxSockAddress
* local
,
1922 // Shutdown and destroy the old socket
1927 m_connected
= false;
1928 m_establishing
= false;
1930 // Create and set up the new one
1931 wxSocketManager
* const manager
= wxSocketManager::Get();
1932 m_impl
= manager
? manager
->CreateSocket(*this) : NULL
;
1936 // Reuse makes sense for clients too, if we are trying to rebind to the same port
1937 if (GetFlags() & wxSOCKET_REUSEADDR
)
1938 m_impl
->SetReusable();
1939 if (GetFlags() & wxSOCKET_BROADCAST
)
1940 m_impl
->SetBroadcast();
1941 if (GetFlags() & wxSOCKET_NOBIND
)
1942 m_impl
->DontDoBind();
1944 // Bind to the local IP address and port, when provided or if one had been
1946 if ( !local
&& m_localAddress
.GetAddress().IsOk() )
1947 local
= &m_localAddress
;
1950 m_impl
->SetLocal(local
->GetAddress());
1952 m_impl
->SetInitialSocketBuffers(m_initialRecvBufferSize
, m_initialSendBufferSize
);
1954 m_impl
->SetPeer(remote
.GetAddress());
1956 // Finally do create the socket and connect to the peer
1957 const wxSocketError err
= m_impl
->CreateClient(wait
);
1959 if ( err
!= wxSOCKET_NOERROR
)
1961 if ( err
== wxSOCKET_WOULDBLOCK
)
1963 wxASSERT_MSG( !wait
, "shouldn't get this for blocking connect" );
1965 m_establishing
= true;
1975 bool wxSocketClient::Connect(const wxSockAddress
& remote
, bool wait
)
1977 return DoConnect(remote
, NULL
, wait
);
1980 bool wxSocketClient::Connect(const wxSockAddress
& remote
,
1981 const wxSockAddress
& local
,
1984 return DoConnect(remote
, &local
, wait
);
1987 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
)
1991 // this happens if the initial attempt to connect succeeded without
1996 wxCHECK_MSG( m_establishing
&& m_impl
, false,
1997 "No connection establishment attempt in progress" );
1999 // notice that we return true even if DoWait() returned -1, i.e. if an
2000 // error occurred and connection was lost: this is intentional as we should
2001 // return false only if timeout expired without anything happening
2002 return DoWait(seconds
, milliseconds
, wxSOCKET_CONNECTION_FLAG
) != 0;
2005 // ==========================================================================
2007 // ==========================================================================
2009 wxDatagramSocket::wxDatagramSocket( const wxSockAddress
& addr
,
2010 wxSocketFlags flags
)
2011 : wxSocketBase( flags
, wxSOCKET_DATAGRAM
)
2013 // Create the socket
2014 wxSocketManager
* const manager
= wxSocketManager::Get();
2015 m_impl
= manager
? manager
->CreateSocket(*this) : NULL
;
2020 // Setup the socket as non connection oriented
2021 m_impl
->SetLocal(addr
.GetAddress());
2022 if (flags
& wxSOCKET_REUSEADDR
)
2024 m_impl
->SetReusable();
2026 if (GetFlags() & wxSOCKET_BROADCAST
)
2028 m_impl
->SetBroadcast();
2030 if (GetFlags() & wxSOCKET_NOBIND
)
2032 m_impl
->DontDoBind();
2035 if ( m_impl
->CreateUDP() != wxSOCKET_NOERROR
)
2041 // Initialize all stuff
2042 m_connected
= false;
2043 m_establishing
= false;
2046 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
,
2055 wxDatagramSocket
& wxDatagramSocket::SendTo( const wxSockAddress
& addr
,
2059 wxASSERT_MSG( m_impl
, wxT("Socket not initialised") );
2061 m_impl
->SetPeer(addr
.GetAddress());
2066 // ==========================================================================
2068 // ==========================================================================
2070 class wxSocketModule
: public wxModule
2073 virtual bool OnInit()
2075 // wxSocketBase will call Initialize() itself only if sockets are
2076 // really used, don't do it from here
2080 virtual void OnExit()
2082 if ( wxSocketBase::IsInitialized() )
2083 wxSocketBase::Shutdown();
2087 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
2090 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)
2092 #if defined(wxUSE_SELECT_DISPATCHER) && wxUSE_SELECT_DISPATCHER
2093 // NOTE: we need to force linking against socketiohandler.cpp otherwise in
2094 // static builds of wxWidgets the ManagerSetter::ManagerSetter ctor
2095 // contained there wouldn't be ever called
2096 wxFORCE_LINK_MODULE( socketiohandler
)
2099 // same for ManagerSetter in the MSW file
2101 wxFORCE_LINK_MODULE( mswsocket
)
2104 // and for OSXManagerSetter in the OS X one
2106 wxFORCE_LINK_MODULE( osxsocket
)
2109 #endif // wxUSE_SOCKETS