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 // License: 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)
76 // ctor disables the given signal
78 : m_handler(signal(sig
, SIG_IGN
)),
83 // dtor restores the old handler
86 signal(m_sig
, m_handler
);
90 const sighandler_t m_handler
;
93 wxDECLARE_NO_COPY_CLASS(IgnoreSignal
);
95 } // anonymous namespace
97 #define wxNEEDS_IGNORE_SIGPIPE
98 #endif // Unix without SO_NOSIGPIPE
100 #define wxSOCKET_MSG_NOSIGNAL 0
103 // DLL options compatibility check:
104 #include "wx/build.h"
105 WX_CHECK_BUILD_OPTIONS("wxNet")
107 // --------------------------------------------------------------------------
108 // macros and constants
109 // --------------------------------------------------------------------------
112 wxDEFINE_EVENT(wxEVT_SOCKET
, wxSocketEvent
);
115 #define MAX_DISCARD_SIZE (10 * 1024)
117 #define wxTRACE_Socket _T("wxSocket")
119 // --------------------------------------------------------------------------
121 // --------------------------------------------------------------------------
123 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
124 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
125 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
126 IMPLEMENT_CLASS(wxDatagramSocket
, wxSocketBase
)
127 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
129 // ----------------------------------------------------------------------------
131 // ----------------------------------------------------------------------------
136 void SetTimeValFromMS(timeval
& tv
, unsigned long ms
)
138 tv
.tv_sec
= (ms
/ 1000);
139 tv
.tv_usec
= (ms
% 1000) * 1000;
142 } // anonymous namespace
144 // --------------------------------------------------------------------------
146 // --------------------------------------------------------------------------
148 class wxSocketState
: public wxObject
151 wxSocketFlags m_flags
;
152 wxSocketEventFlags m_eventmask
;
157 wxSocketState() : wxObject() {}
159 wxDECLARE_NO_COPY_CLASS(wxSocketState
);
162 // wxSocketWaitModeChanger: temporarily change the socket flags affecting its
164 class wxSocketWaitModeChanger
167 // temporarily set the flags to include the flag value which may be either
168 // wxSOCKET_NOWAIT or wxSOCKET_WAITALL
169 wxSocketWaitModeChanger(wxSocketBase
*socket
, int flag
)
171 m_oldflags(socket
->GetFlags())
174 wxASSERT_MSG( flag
== wxSOCKET_WAITALL
|| flag
== wxSOCKET_NOWAIT
,
177 // preserve wxSOCKET_BLOCK value when switching to wxSOCKET_WAITALL
178 // mode but not when switching to wxSOCKET_NOWAIT as the latter is
179 // incompatible with wxSOCKET_BLOCK
180 if ( flag
!= wxSOCKET_NOWAIT
)
181 flag
|= m_oldflags
& wxSOCKET_BLOCK
;
183 socket
->SetFlags(flag
);
186 ~wxSocketWaitModeChanger()
188 m_socket
->SetFlags(m_oldflags
);
192 wxSocketBase
* const m_socket
;
193 const int m_oldflags
;
195 wxDECLARE_NO_COPY_CLASS(wxSocketWaitModeChanger
);
198 // wxSocketRead/WriteGuard are instantiated before starting reading
199 // from/writing to the socket
200 class wxSocketReadGuard
203 wxSocketReadGuard(wxSocketBase
*socket
)
206 wxASSERT_MSG( !m_socket
->m_reading
, "read reentrancy?" );
208 m_socket
->m_reading
= true;
213 m_socket
->m_reading
= false;
215 m_socket
->m_impl
->ReenableEvents(wxSOCKET_INPUT_FLAG
);
219 wxSocketBase
* const m_socket
;
221 wxDECLARE_NO_COPY_CLASS(wxSocketReadGuard
);
224 class wxSocketWriteGuard
227 wxSocketWriteGuard(wxSocketBase
*socket
)
230 wxASSERT_MSG( !m_socket
->m_writing
, "write reentrancy?" );
232 m_socket
->m_writing
= true;
234 m_socket
->m_impl
->ReenableEvents(wxSOCKET_OUTPUT_FLAG
);
237 ~wxSocketWriteGuard()
239 m_socket
->m_writing
= false;
243 wxSocketBase
* const m_socket
;
245 wxDECLARE_NO_COPY_CLASS(wxSocketWriteGuard
);
248 // ============================================================================
250 // ============================================================================
252 wxSocketManager
*wxSocketManager::ms_manager
= NULL
;
255 void wxSocketManager::Set(wxSocketManager
*manager
)
257 wxASSERT_MSG( !ms_manager
, "too late to set manager now" );
259 ms_manager
= manager
;
263 void wxSocketManager::Init()
265 wxASSERT_MSG( !ms_manager
, "shouldn't be initialized twice" );
268 Details: Initialize() creates a hidden window as a sink for socket
269 events, such as 'read completed'. wxMSW has only one message loop
270 for the main thread. If Initialize is called in a secondary thread,
271 the socket window will be created for the secondary thread, but
272 since there is no message loop on this thread, it will never
273 receive events and all socket operations will time out.
274 BTW, the main thread must not be stopped using sleep or block
275 on a semaphore (a bad idea in any case) or socket operations
278 On the Mac side, Initialize() stores a pointer to the CFRunLoop for
279 the main thread. Because secondary threads do not have run loops,
280 adding event notifications to the "Current" loop would have no
281 effect at all, events would never fire.
283 wxASSERT_MSG( wxIsMainThread(),
284 "sockets must be initialized from the main thread" );
286 wxAppConsole
* const app
= wxAppConsole::GetInstance();
287 wxCHECK_RET( app
, "sockets can't be initialized without wxApp" );
289 ms_manager
= app
->GetTraits()->GetSocketManager();
292 // ==========================================================================
294 // ==========================================================================
296 wxSocketImpl::wxSocketImpl(wxSocketBase
& wxsocket
)
297 : m_wxsocket(&wxsocket
)
299 m_fd
= INVALID_SOCKET
;
300 m_error
= wxSOCKET_NOERROR
;
304 SetTimeout(wxsocket
.GetTimeout() * 1000);
306 m_establishing
= false;
310 m_initialRecvBufferSize
= -1;
311 m_initialSendBufferSize
= -1;
314 wxSocketImpl::~wxSocketImpl()
316 if ( m_fd
!= INVALID_SOCKET
)
320 bool wxSocketImpl::PreCreateCheck(const wxSockAddressImpl
& addr
)
322 if ( m_fd
!= INVALID_SOCKET
)
324 m_error
= wxSOCKET_INVSOCK
;
330 m_error
= wxSOCKET_INVADDR
;
337 void wxSocketImpl::PostCreation()
339 // FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option
341 EnableSocketOption(SO_NOSIGPIPE
);
345 EnableSocketOption(SO_REUSEADDR
);
349 wxASSERT_MSG( !m_stream
, "broadcasting is for datagram sockets only" );
351 EnableSocketOption(SO_BROADCAST
);
354 if ( m_initialRecvBufferSize
>= 0 )
355 SetSocketOption(SO_RCVBUF
, m_initialRecvBufferSize
);
356 if ( m_initialSendBufferSize
>= 0 )
357 SetSocketOption(SO_SNDBUF
, m_initialSendBufferSize
);
359 // we always put our sockets in unblocked mode and handle blocking
360 // ourselves in DoRead/Write() if wxSOCKET_WAITALL is specified
361 UnblockAndRegisterWithEventLoop();
364 wxSocketError
wxSocketImpl::UpdateLocalAddress()
366 WX_SOCKLEN_T lenAddr
= m_local
.GetLen();
367 if ( getsockname(m_fd
, m_local
.GetWritableAddr(), &lenAddr
) != 0 )
370 m_error
= wxSOCKET_IOERR
;
374 return wxSOCKET_NOERROR
;
377 wxSocketError
wxSocketImpl::CreateServer()
379 if ( !PreCreateCheck(m_local
) )
385 // do create the socket
386 m_fd
= socket(m_local
.GetFamily(), SOCK_STREAM
, 0);
388 if ( m_fd
== INVALID_SOCKET
)
390 m_error
= wxSOCKET_IOERR
;
391 return wxSOCKET_IOERR
;
396 // and then bind to and listen on it
398 // FIXME: should we test for m_dobind here?
399 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
400 m_error
= wxSOCKET_IOERR
;
404 if ( listen(m_fd
, 5) != 0 )
405 m_error
= wxSOCKET_IOERR
;
414 // finally retrieve the address we effectively bound to
415 return UpdateLocalAddress();
418 wxSocketError
wxSocketImpl::CreateClient(bool wait
)
420 if ( !PreCreateCheck(m_peer
) )
423 m_fd
= socket(m_peer
.GetFamily(), SOCK_STREAM
, 0);
425 if ( m_fd
== INVALID_SOCKET
)
427 m_error
= wxSOCKET_IOERR
;
428 return wxSOCKET_IOERR
;
433 // If a local address has been set, then bind to it before calling connect
434 if ( m_local
.IsOk() )
436 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
439 m_error
= wxSOCKET_IOERR
;
445 int rc
= connect(m_fd
, m_peer
.GetAddr(), m_peer
.GetLen());
446 if ( rc
== SOCKET_ERROR
)
448 wxSocketError err
= GetLastError();
449 if ( err
== wxSOCKET_WOULDBLOCK
)
451 m_establishing
= true;
453 // block waiting for connection if we should (otherwise just return
454 // wxSOCKET_WOULDBLOCK to the caller)
457 err
= SelectWithTimeout(wxSOCKET_CONNECTION_FLAG
)
460 m_establishing
= false;
468 m_error
= wxSOCKET_NOERROR
;
475 wxSocketError
wxSocketImpl::CreateUDP()
477 if ( !PreCreateCheck(m_local
) )
483 m_fd
= socket(m_local
.GetFamily(), SOCK_DGRAM
, 0);
485 if ( m_fd
== INVALID_SOCKET
)
487 m_error
= wxSOCKET_IOERR
;
488 return wxSOCKET_IOERR
;
495 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
498 m_error
= wxSOCKET_IOERR
;
502 return UpdateLocalAddress();
505 return wxSOCKET_NOERROR
;
508 wxSocketImpl
*wxSocketImpl::Accept(wxSocketBase
& wxsocket
)
510 wxSockAddressStorage from
;
511 WX_SOCKLEN_T fromlen
= sizeof(from
);
512 const SOCKET fd
= accept(m_fd
, &from
.addr
, &fromlen
);
514 // accepting is similar to reading in the sense that it resets "ready for
515 // read" flag on the socket
516 ReenableEvents(wxSOCKET_INPUT_FLAG
);
518 if ( fd
== INVALID_SOCKET
)
521 wxSocketImpl
* const sock
= Create(wxsocket
);
523 sock
->m_peer
= wxSockAddressImpl(from
.addr
, fromlen
);
525 sock
->UnblockAndRegisterWithEventLoop();
531 void wxSocketImpl::Close()
533 if ( m_fd
!= INVALID_SOCKET
)
536 m_fd
= INVALID_SOCKET
;
540 void wxSocketImpl::Shutdown()
542 if ( m_fd
!= INVALID_SOCKET
)
544 shutdown(m_fd
, 1 /* SD_SEND */);
550 * Sets the timeout for blocking calls. Time is expressed in
553 void wxSocketImpl::SetTimeout(unsigned long millis
)
555 SetTimeValFromMS(m_timeout
, millis
);
558 void wxSocketImpl::NotifyOnStateChange(wxSocketNotify event
)
560 m_wxsocket
->OnRequest(event
);
563 /* Address handling */
564 wxSocketError
wxSocketImpl::SetLocal(const wxSockAddressImpl
& local
)
566 /* the socket must be initialized, or it must be a server */
567 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
569 m_error
= wxSOCKET_INVSOCK
;
570 return wxSOCKET_INVSOCK
;
575 m_error
= wxSOCKET_INVADDR
;
576 return wxSOCKET_INVADDR
;
581 return wxSOCKET_NOERROR
;
584 wxSocketError
wxSocketImpl::SetPeer(const wxSockAddressImpl
& peer
)
588 m_error
= wxSOCKET_INVADDR
;
589 return wxSOCKET_INVADDR
;
594 return wxSOCKET_NOERROR
;
597 const wxSockAddressImpl
& wxSocketImpl::GetLocal()
599 if ( !m_local
.IsOk() )
600 UpdateLocalAddress();
605 // ----------------------------------------------------------------------------
607 // ----------------------------------------------------------------------------
609 // this macro wraps the given expression (normally a syscall) in a loop which
610 // ignores any interruptions, i.e. reevaluates it again if it failed and errno
613 #define DO_WHILE_EINTR( rc, syscall ) \
617 while ( rc == -1 && errno == EINTR )
619 #define DO_WHILE_EINTR( rc, syscall ) rc = (syscall)
622 int wxSocketImpl::RecvStream(void *buffer
, int size
)
625 DO_WHILE_EINTR( ret
, recv(m_fd
, static_cast<char *>(buffer
), size
, 0) );
629 // receiving 0 bytes for a TCP socket indicates that the connection was
630 // closed by peer so shut down our end as well (for UDP sockets empty
631 // datagrams are also possible)
632 m_establishing
= false;
633 NotifyOnStateChange(wxSOCKET_LOST
);
637 // do not return an error in this case however
643 int wxSocketImpl::SendStream(const void *buffer
, int size
)
645 #ifdef wxNEEDS_IGNORE_SIGPIPE
646 IgnoreSignal
ignore(SIGPIPE
);
650 DO_WHILE_EINTR( ret
, send(m_fd
, static_cast<const char *>(buffer
), size
,
651 wxSOCKET_MSG_NOSIGNAL
) );
656 int wxSocketImpl::RecvDgram(void *buffer
, int size
)
658 wxSockAddressStorage from
;
659 WX_SOCKLEN_T fromlen
= sizeof(from
);
662 DO_WHILE_EINTR( ret
, recvfrom(m_fd
, static_cast<char *>(buffer
), size
,
663 0, &from
.addr
, &fromlen
) );
665 if ( ret
== SOCKET_ERROR
)
668 m_peer
= wxSockAddressImpl(from
.addr
, fromlen
);
669 if ( !m_peer
.IsOk() )
675 int wxSocketImpl::SendDgram(const void *buffer
, int size
)
677 if ( !m_peer
.IsOk() )
679 m_error
= wxSOCKET_INVADDR
;
684 DO_WHILE_EINTR( ret
, sendto(m_fd
, static_cast<const char *>(buffer
), size
,
685 0, m_peer
.GetAddr(), m_peer
.GetLen()) );
690 int wxSocketImpl::Read(void *buffer
, int size
)
692 // server sockets can't be used for IO, only to accept new connections
693 if ( m_fd
== INVALID_SOCKET
|| m_server
)
695 m_error
= wxSOCKET_INVSOCK
;
699 int ret
= m_stream
? RecvStream(buffer
, size
)
700 : RecvDgram(buffer
, size
);
702 m_error
= ret
== SOCKET_ERROR
? GetLastError() : wxSOCKET_NOERROR
;
707 int wxSocketImpl::Write(const void *buffer
, int size
)
709 if ( m_fd
== INVALID_SOCKET
|| m_server
)
711 m_error
= wxSOCKET_INVSOCK
;
715 int ret
= m_stream
? SendStream(buffer
, size
)
716 : SendDgram(buffer
, size
);
718 m_error
= ret
== SOCKET_ERROR
? GetLastError() : wxSOCKET_NOERROR
;
723 // ==========================================================================
725 // ==========================================================================
727 // --------------------------------------------------------------------------
728 // Initialization and shutdown
729 // --------------------------------------------------------------------------
731 // FIXME-MT: all this is MT-unsafe, of course, we should protect all accesses
732 // to m_countInit with a crit section
733 size_t wxSocketBase::m_countInit
= 0;
735 bool wxSocketBase::IsInitialized()
737 return m_countInit
> 0;
740 bool wxSocketBase::Initialize()
742 if ( !m_countInit
++ )
744 wxSocketManager
* const manager
= wxSocketManager::Get();
745 if ( !manager
|| !manager
->OnInit() )
756 void wxSocketBase::Shutdown()
758 // we should be initialized
759 wxASSERT_MSG( m_countInit
> 0, _T("extra call to Shutdown()") );
760 if ( --m_countInit
== 0 )
762 wxSocketManager
* const manager
= wxSocketManager::Get();
763 wxCHECK_RET( manager
, "should have a socket manager" );
769 // --------------------------------------------------------------------------
771 // --------------------------------------------------------------------------
773 void wxSocketBase::Init()
776 m_type
= wxSOCKET_UNINIT
;
787 m_beingDeleted
= false;
802 if ( !IsInitialized() )
804 // this Initialize() will be undone by wxSocketModule::OnExit(), all
805 // the other calls to it should be matched by a call to Shutdown()
807 wxLogError("Cannot initialize wxSocketBase");
811 wxSocketBase::wxSocketBase()
816 wxSocketBase::wxSocketBase(wxSocketFlags flags
, wxSocketType type
)
825 wxSocketBase::~wxSocketBase()
827 // Just in case the app called Destroy() *and* then deleted the socket
828 // immediately: don't leave dangling pointers.
829 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
831 traits
->RemoveFromPendingDelete(this);
833 // Shutdown and close the socket
837 // Destroy the implementation object
840 // Free the pushback buffer
845 bool wxSocketBase::Destroy()
847 // Delayed destruction: the socket will be deleted during the next idle
848 // loop iteration. This ensures that all pending events have been
850 m_beingDeleted
= true;
852 // Shutdown and close the socket
855 // Suppress events from now on
858 // schedule this object for deletion
859 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
862 // let the traits object decide what to do with us
863 traits
->ScheduleForDestroy(this);
865 else // no app or no traits
867 // in wxBase we might have no app object at all, don't leak memory
874 // ----------------------------------------------------------------------------
876 // ----------------------------------------------------------------------------
878 void wxSocketBase::SetError(wxSocketError error
)
880 m_impl
->m_error
= error
;
883 wxSocketError
wxSocketBase::LastError() const
885 return m_impl
->GetError();
888 // --------------------------------------------------------------------------
890 // --------------------------------------------------------------------------
892 // The following IO operations update m_lcount:
893 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
894 bool wxSocketBase::Close()
896 // Interrupt pending waits
902 m_establishing
= false;
906 void wxSocketBase::ShutdownOutput()
912 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
)
914 wxSocketReadGuard
read(this);
916 m_lcount
= DoRead(buffer
, nbytes
);
921 wxUint32
wxSocketBase::DoRead(void* buffer_
, wxUint32 nbytes
)
923 wxCHECK_MSG( m_impl
, 0, "socket must be valid" );
925 // We use pointer arithmetic here which doesn't work with void pointers.
926 char *buffer
= static_cast<char *>(buffer_
);
927 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
929 // Try the push back buffer first, even before checking whether the socket
930 // is valid to allow reading previously pushed back data from an already
932 wxUint32 total
= GetPushback(buffer
, nbytes
, false);
938 // our socket is non-blocking so Read() will return immediately if
939 // there is nothing to read yet and it's more efficient to try it first
940 // before entering DoWait() which is going to start dispatching GUI
941 // events and, even more importantly, we must do this under Windows
942 // where we're not going to get notifications about socket being ready
943 // for reading before we read all the existing data from it
944 const int ret
= m_connected
? m_impl
->Read(buffer
, nbytes
) : 0;
947 if ( m_impl
->GetLastError() == wxSOCKET_WOULDBLOCK
)
949 // if we don't want to wait, just return immediately
950 if ( m_flags
& wxSOCKET_NOWAIT
)
953 // otherwise wait until the socket becomes ready for reading or
954 // an error occurs on it
955 if ( !DoWaitWithTimeout(wxSOCKET_INPUT_FLAG
) )
957 // and exit if the timeout elapsed before it did
958 SetError(wxSOCKET_TIMEDOUT
);
967 SetError(wxSOCKET_IOERR
);
973 // for connection-oriented (e.g. TCP) sockets we can only read
974 // 0 bytes if the other end has been closed, and for connectionless
975 // ones (UDP) this flag doesn't make sense anyhow so we can set it
976 // to true too without doing any harm
979 // we're not going to read anything else and so if we haven't read
980 // anything (or not everything in wxSOCKET_WAITALL case) already,
982 if ( (m_flags
& wxSOCKET_WAITALL
) || !total
)
983 SetError(wxSOCKET_IOERR
);
989 // if we are happy to read something and not the entire nbytes bytes,
991 if ( !(m_flags
& wxSOCKET_WAITALL
) )
1001 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
)
1005 unsigned char sig
[4];
1006 unsigned char len
[4];
1009 wxSocketReadGuard
read(this);
1011 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_WAITALL
);
1014 if ( DoRead(&msg
, sizeof(msg
)) == sizeof(msg
) )
1016 wxUint32 sig
= (wxUint32
)msg
.sig
[0];
1017 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
1018 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
1019 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
1021 if ( sig
== 0xfeeddead )
1023 wxUint32 len
= (wxUint32
)msg
.len
[0];
1024 len
|= (wxUint32
)(msg
.len
[1] << 8);
1025 len
|= (wxUint32
)(msg
.len
[2] << 16);
1026 len
|= (wxUint32
)(msg
.len
[3] << 24);
1031 len2
= len
- nbytes
;
1037 // Don't attempt to read if the msg was zero bytes long.
1038 m_lcount
= len
? DoRead(buffer
, len
) : 0;
1042 char discard_buffer
[MAX_DISCARD_SIZE
];
1045 // NOTE: discarded bytes don't add to m_lcount.
1048 discard_len
= len2
> MAX_DISCARD_SIZE
1051 discard_len
= DoRead(discard_buffer
, (wxUint32
)discard_len
);
1052 len2
-= (wxUint32
)discard_len
;
1054 while ((discard_len
> 0) && len2
);
1057 if ( !len2
&& DoRead(&msg
, sizeof(msg
)) == sizeof(msg
) )
1059 sig
= (wxUint32
)msg
.sig
[0];
1060 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
1061 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
1062 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
1064 if ( sig
== 0xdeadfeed )
1071 SetError(wxSOCKET_IOERR
);
1076 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
)
1078 wxSocketReadGuard
read(this);
1080 m_lcount
= DoRead(buffer
, nbytes
);
1082 Pushback(buffer
, m_lcount
);
1087 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
)
1089 wxSocketWriteGuard
write(this);
1091 m_lcount
= DoWrite(buffer
, nbytes
);
1096 // This function is a mirror image of DoRead() except that it doesn't use the
1097 // push back buffer and doesn't treat 0 return value specially (normally this
1098 // shouldn't happen at all here), so please see comments there for explanations
1099 wxUint32
wxSocketBase::DoWrite(const void *buffer_
, wxUint32 nbytes
)
1101 wxCHECK_MSG( m_impl
, 0, "socket must be valid" );
1103 const char *buffer
= static_cast<const char *>(buffer_
);
1104 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1111 if ( (m_flags
& wxSOCKET_WAITALL
) || !total
)
1112 SetError(wxSOCKET_IOERR
);
1116 const int ret
= m_impl
->Write(buffer
, nbytes
);
1119 if ( m_impl
->GetLastError() == wxSOCKET_WOULDBLOCK
)
1121 if ( m_flags
& wxSOCKET_NOWAIT
)
1124 if ( !DoWaitWithTimeout(wxSOCKET_OUTPUT_FLAG
) )
1126 SetError(wxSOCKET_TIMEDOUT
);
1132 else // "real" error
1134 SetError(wxSOCKET_IOERR
);
1141 if ( !(m_flags
& wxSOCKET_WAITALL
) )
1151 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
)
1155 unsigned char sig
[4];
1156 unsigned char len
[4];
1159 wxSocketWriteGuard
write(this);
1161 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_WAITALL
);
1163 msg
.sig
[0] = (unsigned char) 0xad;
1164 msg
.sig
[1] = (unsigned char) 0xde;
1165 msg
.sig
[2] = (unsigned char) 0xed;
1166 msg
.sig
[3] = (unsigned char) 0xfe;
1168 msg
.len
[0] = (unsigned char) (nbytes
& 0xff);
1169 msg
.len
[1] = (unsigned char) ((nbytes
>> 8) & 0xff);
1170 msg
.len
[2] = (unsigned char) ((nbytes
>> 16) & 0xff);
1171 msg
.len
[3] = (unsigned char) ((nbytes
>> 24) & 0xff);
1174 if ( DoWrite(&msg
, sizeof(msg
)) == sizeof(msg
) )
1176 m_lcount
= DoWrite(buffer
, nbytes
);
1177 if ( m_lcount
== nbytes
)
1179 msg
.sig
[0] = (unsigned char) 0xed;
1180 msg
.sig
[1] = (unsigned char) 0xfe;
1181 msg
.sig
[2] = (unsigned char) 0xad;
1182 msg
.sig
[3] = (unsigned char) 0xde;
1186 msg
.len
[3] = (char) 0;
1188 if ( DoWrite(&msg
, sizeof(msg
)) == sizeof(msg
))
1194 SetError(wxSOCKET_IOERR
);
1199 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
)
1202 Pushback(buffer
, nbytes
);
1204 SetError(wxSOCKET_NOERROR
);
1210 wxSocketBase
& wxSocketBase::Discard()
1212 char *buffer
= new char[MAX_DISCARD_SIZE
];
1216 wxSocketReadGuard
read(this);
1218 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_NOWAIT
);
1222 ret
= DoRead(buffer
, MAX_DISCARD_SIZE
);
1225 while (ret
== MAX_DISCARD_SIZE
);
1229 SetError(wxSOCKET_NOERROR
);
1234 // --------------------------------------------------------------------------
1236 // --------------------------------------------------------------------------
1239 This function will check for the events specified in the flags parameter,
1240 and it will return a mask indicating which operations can be performed.
1242 wxSocketEventFlags
wxSocketImpl::Select(wxSocketEventFlags flags
,
1243 const timeval
*timeout
)
1245 if ( m_fd
== INVALID_SOCKET
)
1246 return (wxSOCKET_LOST_FLAG
& flags
);
1252 tv
.tv_sec
= tv
.tv_usec
= 0;
1254 // prepare the FD sets, passing NULL for the one(s) we don't use
1256 readfds
, *preadfds
= NULL
,
1257 writefds
, *pwritefds
= NULL
,
1258 exceptfds
; // always want to know about errors
1260 if ( flags
& wxSOCKET_INPUT_FLAG
)
1262 preadfds
= &readfds
;
1263 wxFD_ZERO(preadfds
);
1264 wxFD_SET(m_fd
, preadfds
);
1267 // when using non-blocking connect() the socket becomes connected
1268 // (successfully or not) when it becomes writable
1269 if ( flags
& (wxSOCKET_OUTPUT_FLAG
| wxSOCKET_CONNECTION_FLAG
) )
1271 pwritefds
= &writefds
;
1272 wxFD_ZERO(pwritefds
);
1273 wxFD_SET(m_fd
, pwritefds
);
1276 wxFD_ZERO(&exceptfds
);
1277 wxFD_SET(m_fd
, &exceptfds
);
1279 const int rc
= select(m_fd
+ 1, preadfds
, pwritefds
, &exceptfds
, &tv
);
1281 // check for errors first
1282 if ( rc
== -1 || wxFD_ISSET(m_fd
, &exceptfds
) )
1284 m_establishing
= false;
1286 return wxSOCKET_LOST_FLAG
& flags
;
1292 wxASSERT_MSG( rc
== 1, "unexpected select() return value" );
1294 wxSocketEventFlags detected
= 0;
1295 if ( preadfds
&& wxFD_ISSET(m_fd
, preadfds
) )
1296 detected
|= wxSOCKET_INPUT_FLAG
;
1298 if ( pwritefds
&& wxFD_ISSET(m_fd
, pwritefds
) )
1300 // check for the case of non-blocking connect()
1301 if ( m_establishing
&& !m_server
)
1304 SOCKOPTLEN_T len
= sizeof(error
);
1305 m_establishing
= false;
1306 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1309 detected
= wxSOCKET_LOST_FLAG
;
1311 detected
|= wxSOCKET_CONNECTION_FLAG
;
1313 else // not called to get non-blocking connect() status
1315 detected
|= wxSOCKET_OUTPUT_FLAG
;
1319 return detected
& flags
;
1323 wxSocketBase::DoWait(long seconds
, long milliseconds
, wxSocketEventFlags flags
)
1325 // Use either the provided timeout or the default timeout value associated
1326 // with this socket.
1328 // TODO: allow waiting forever, see #9443
1329 const long timeout
= seconds
== -1 ? m_timeout
* 1000
1330 : seconds
* 1000 + milliseconds
;
1332 return DoWait(timeout
, flags
);
1336 wxSocketBase::DoWait(long timeout
, wxSocketEventFlags flags
)
1338 wxCHECK_MSG( m_impl
, -1, "can't wait on invalid socket" );
1340 // we're never going to become ready if we're not connected (any more)
1341 if ( !m_connected
&& !m_establishing
)
1344 // This can be set to true from Interrupt() to exit this function a.s.a.p.
1345 m_interrupt
= false;
1348 const wxMilliClock_t timeEnd
= wxGetLocalTimeMillis() + timeout
;
1350 // Get the active event loop which we'll use for the message dispatching
1351 // when running in the main thread unless this was explicitly disabled by
1352 // setting wxSOCKET_BLOCK flag
1353 wxEventLoopBase
*eventLoop
;
1354 if ( !(m_flags
& wxSOCKET_BLOCK
) && wxIsMainThread() )
1356 eventLoop
= wxEventLoop::GetActive();
1358 else // in worker thread
1360 // We never dispatch messages from threads other than the main one.
1364 // Make sure the events we're interested in are enabled before waiting for
1365 // them: this is really necessary here as otherwise this could happen:
1366 // 1. DoRead(wxSOCKET_WAITALL) is called
1367 // 2. There is nothing to read so DoWait(wxSOCKET_INPUT_FLAG) is called
1368 // 3. Some, but not all data appears, wxSocketImplUnix::OnReadWaiting()
1369 // is called and wxSOCKET_INPUT_FLAG events are disabled in it
1370 // 4. Because of wxSOCKET_WAITALL we call DoWait() again but the events
1371 // are still disabled and we block forever
1373 // More elegant solution would be nice but for now simply re-enabling the
1374 // events here will do
1375 m_impl
->ReenableEvents(flags
& (wxSOCKET_INPUT_FLAG
| wxSOCKET_OUTPUT_FLAG
));
1378 // Wait until we receive the event we're waiting for or the timeout expires
1379 // (but note that we always execute the loop at least once, even if timeout
1380 // is 0 as this is used for polling)
1382 for ( bool firstTime
= true; !m_interrupt
; firstTime
= false )
1384 long timeLeft
= wxMilliClockToLong(timeEnd
- wxGetLocalTimeMillis());
1393 wxSocketEventFlags events
;
1396 // reset them before starting to wait
1399 eventLoop
->DispatchTimeout(timeLeft
);
1401 events
= m_eventsgot
;
1403 else // no event loop or waiting in another thread
1405 // as explained below, we should always check for wxSOCKET_LOST_FLAG
1407 SetTimeValFromMS(tv
, timeLeft
);
1408 events
= m_impl
->Select(flags
| wxSOCKET_LOST_FLAG
, &tv
);
1411 // always check for wxSOCKET_LOST_FLAG, even if flags doesn't include
1412 // it, as continuing to wait for anything else after getting it is
1414 if ( events
& wxSOCKET_LOST_FLAG
)
1416 m_connected
= false;
1417 m_establishing
= false;
1422 // otherwise mask out the bits we're not interested in
1425 // Incoming connection (server) or connection established (client)?
1426 if ( events
& wxSOCKET_CONNECTION_FLAG
)
1429 m_establishing
= false;
1434 // Data available or output buffer ready?
1435 if ( (events
& wxSOCKET_INPUT_FLAG
) || (events
& wxSOCKET_OUTPUT_FLAG
) )
1445 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
1447 return DoWait(seconds
, milliseconds
,
1448 wxSOCKET_INPUT_FLAG
|
1449 wxSOCKET_OUTPUT_FLAG
|
1450 wxSOCKET_CONNECTION_FLAG
) != 0;
1453 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
1455 // Check pushback buffer before entering DoWait
1459 // Check if the socket is not already ready for input, if it is, there is
1460 // no need to start waiting for it (worse, we'll actually never get a
1461 // notification about the socket becoming ready if it is already under
1463 if ( m_impl
->Select(wxSOCKET_INPUT_FLAG
) )
1466 return DoWait(seconds
, milliseconds
, wxSOCKET_INPUT_FLAG
) != 0;
1470 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
1472 if ( m_impl
->Select(wxSOCKET_OUTPUT_FLAG
) )
1475 return DoWait(seconds
, milliseconds
, wxSOCKET_OUTPUT_FLAG
) != 0;
1478 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
1480 return DoWait(seconds
, milliseconds
, wxSOCKET_LOST_FLAG
) == -1;
1483 // --------------------------------------------------------------------------
1485 // --------------------------------------------------------------------------
1488 // Get local or peer address
1491 bool wxSocketBase::GetPeer(wxSockAddress
& addr
) const
1493 wxCHECK_MSG( m_impl
, false, "invalid socket" );
1495 const wxSockAddressImpl
& peer
= m_impl
->GetPeer();
1499 addr
.SetAddress(peer
);
1504 bool wxSocketBase::GetLocal(wxSockAddress
& addr
) const
1506 wxCHECK_MSG( m_impl
, false, "invalid socket" );
1508 const wxSockAddressImpl
& local
= m_impl
->GetLocal();
1509 if ( !local
.IsOk() )
1512 addr
.SetAddress(local
);
1518 // Save and restore socket state
1521 void wxSocketBase::SaveState()
1523 wxSocketState
*state
;
1525 state
= new wxSocketState();
1527 state
->m_flags
= m_flags
;
1528 state
->m_notify
= m_notify
;
1529 state
->m_eventmask
= m_eventmask
;
1530 state
->m_clientData
= m_clientData
;
1532 m_states
.Append(state
);
1535 void wxSocketBase::RestoreState()
1537 wxList::compatibility_iterator node
;
1538 wxSocketState
*state
;
1540 node
= m_states
.GetLast();
1544 state
= (wxSocketState
*)node
->GetData();
1546 m_flags
= state
->m_flags
;
1547 m_notify
= state
->m_notify
;
1548 m_eventmask
= state
->m_eventmask
;
1549 m_clientData
= state
->m_clientData
;
1551 m_states
.Erase(node
);
1556 // Timeout and flags
1559 void wxSocketBase::SetTimeout(long seconds
)
1561 m_timeout
= seconds
;
1564 m_impl
->SetTimeout(m_timeout
* 1000);
1567 void wxSocketBase::SetFlags(wxSocketFlags flags
)
1569 // Do some sanity checking on the flags used: not all values can be used
1571 wxASSERT_MSG( !(flags
& wxSOCKET_NOWAIT
) ||
1572 !(flags
& (wxSOCKET_WAITALL
| wxSOCKET_BLOCK
)),
1573 "Using wxSOCKET_WAITALL or wxSOCKET_BLOCK with "
1574 "wxSOCKET_NOWAIT doesn't make sense" );
1580 // --------------------------------------------------------------------------
1582 // --------------------------------------------------------------------------
1584 void wxSocketBase::OnRequest(wxSocketNotify notification
)
1586 wxSocketEventFlags flag
= 0;
1587 switch ( notification
)
1589 case wxSOCKET_INPUT
:
1590 flag
= wxSOCKET_INPUT_FLAG
;
1593 case wxSOCKET_OUTPUT
:
1594 flag
= wxSOCKET_OUTPUT_FLAG
;
1597 case wxSOCKET_CONNECTION
:
1598 flag
= wxSOCKET_CONNECTION_FLAG
;
1602 flag
= wxSOCKET_LOST_FLAG
;
1606 wxFAIL_MSG( "unknown wxSocket notification" );
1609 // if we lost the connection the socket is now closed
1610 if ( notification
== wxSOCKET_LOST
)
1613 // remember the events which were generated for this socket, we're going to
1614 // use this in DoWait()
1615 m_eventsgot
|= flag
;
1617 // send the wx event if enabled and we're interested in it
1618 if ( m_notify
&& (m_eventmask
& flag
) && m_handler
)
1620 // don't generate the events when we're inside DoWait() called from our
1621 // own code as we are going to consume the data that has just become
1622 // available ourselves and the user code won't see it at all
1623 if ( (notification
== wxSOCKET_INPUT
&& m_reading
) ||
1624 (notification
== wxSOCKET_OUTPUT
&& m_writing
) )
1629 wxSocketEvent
event(m_id
);
1630 event
.m_event
= notification
;
1631 event
.m_clientData
= m_clientData
;
1632 event
.SetEventObject(this);
1634 m_handler
->AddPendingEvent(event
);
1638 void wxSocketBase::Notify(bool notify
)
1643 void wxSocketBase::SetNotify(wxSocketEventFlags flags
)
1645 m_eventmask
= flags
;
1648 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
)
1650 m_handler
= &handler
;
1654 // --------------------------------------------------------------------------
1656 // --------------------------------------------------------------------------
1658 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
)
1662 if (m_unread
== NULL
)
1663 m_unread
= malloc(size
);
1668 tmp
= malloc(m_unrd_size
+ size
);
1669 memcpy((char *)tmp
+ size
, m_unread
, m_unrd_size
);
1675 m_unrd_size
+= size
;
1677 memcpy(m_unread
, buffer
, size
);
1680 wxUint32
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
)
1682 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1687 if (size
> (m_unrd_size
-m_unrd_cur
))
1688 size
= m_unrd_size
-m_unrd_cur
;
1690 memcpy(buffer
, (char *)m_unread
+ m_unrd_cur
, size
);
1695 if (m_unrd_size
== m_unrd_cur
)
1708 // ==========================================================================
1710 // ==========================================================================
1712 // --------------------------------------------------------------------------
1714 // --------------------------------------------------------------------------
1716 wxSocketServer::wxSocketServer(const wxSockAddress
& addr
,
1717 wxSocketFlags flags
)
1718 : wxSocketBase(flags
, wxSOCKET_SERVER
)
1720 wxLogTrace( wxTRACE_Socket
, _T("Opening wxSocketServer") );
1722 m_impl
= wxSocketImpl::Create(*this);
1726 wxLogTrace( wxTRACE_Socket
, _T("*** Failed to create m_impl") );
1730 // Setup the socket as server
1731 m_impl
->SetLocal(addr
.GetAddress());
1733 if (GetFlags() & wxSOCKET_REUSEADDR
) {
1734 m_impl
->SetReusable();
1736 if (GetFlags() & wxSOCKET_BROADCAST
) {
1737 m_impl
->SetBroadcast();
1739 if (GetFlags() & wxSOCKET_NOBIND
) {
1740 m_impl
->DontDoBind();
1743 if (m_impl
->CreateServer() != wxSOCKET_NOERROR
)
1748 wxLogTrace( wxTRACE_Socket
, _T("*** CreateServer() failed") );
1752 wxLogTrace( wxTRACE_Socket
, _T("wxSocketServer on fd %d"), m_impl
->m_fd
);
1755 // --------------------------------------------------------------------------
1757 // --------------------------------------------------------------------------
1759 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
)
1761 if ( !m_impl
|| (m_impl
->m_fd
== INVALID_SOCKET
) || !m_impl
->IsServer() )
1763 wxFAIL_MSG( "can only be called for a valid server socket" );
1765 SetError(wxSOCKET_INVSOCK
);
1772 // wait until we get a connection
1773 if ( !m_impl
->SelectWithTimeout(wxSOCKET_INPUT_FLAG
) )
1775 SetError(wxSOCKET_TIMEDOUT
);
1781 sock
.m_impl
= m_impl
->Accept(sock
);
1785 SetError(m_impl
->GetLastError());
1790 sock
.m_type
= wxSOCKET_BASE
;
1791 sock
.m_connected
= true;
1796 wxSocketBase
*wxSocketServer::Accept(bool wait
)
1798 wxSocketBase
* sock
= new wxSocketBase();
1800 sock
->SetFlags(m_flags
);
1802 if (!AcceptWith(*sock
, wait
))
1811 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
)
1813 return DoWait(seconds
, milliseconds
, wxSOCKET_CONNECTION_FLAG
) == 1;
1816 bool wxSocketBase::GetOption(int level
, int optname
, void *optval
, int *optlen
)
1818 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
1820 SOCKOPTLEN_T lenreal
= *optlen
;
1821 if ( getsockopt(m_impl
->m_fd
, level
, optname
,
1822 static_cast<char *>(optval
), &lenreal
) != 0 )
1831 wxSocketBase::SetOption(int level
, int optname
, const void *optval
, int optlen
)
1833 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
1835 return setsockopt(m_impl
->m_fd
, level
, optname
,
1836 static_cast<const char *>(optval
), optlen
) == 0;
1839 bool wxSocketBase::SetLocal(const wxIPV4address
& local
)
1841 m_localAddress
= local
;
1846 // ==========================================================================
1848 // ==========================================================================
1850 // --------------------------------------------------------------------------
1852 // --------------------------------------------------------------------------
1854 wxSocketClient::wxSocketClient(wxSocketFlags flags
)
1855 : wxSocketBase(flags
, wxSOCKET_CLIENT
)
1857 m_initialRecvBufferSize
=
1858 m_initialSendBufferSize
= -1;
1861 // --------------------------------------------------------------------------
1863 // --------------------------------------------------------------------------
1865 bool wxSocketClient::DoConnect(const wxSockAddress
& remote
,
1866 const wxSockAddress
* local
,
1871 // Shutdown and destroy the old socket
1876 m_connected
= false;
1877 m_establishing
= false;
1879 // Create and set up the new one
1880 m_impl
= wxSocketImpl::Create(*this);
1884 // Reuse makes sense for clients too, if we are trying to rebind to the same port
1885 if (GetFlags() & wxSOCKET_REUSEADDR
)
1886 m_impl
->SetReusable();
1887 if (GetFlags() & wxSOCKET_BROADCAST
)
1888 m_impl
->SetBroadcast();
1889 if (GetFlags() & wxSOCKET_NOBIND
)
1890 m_impl
->DontDoBind();
1892 // Bind to the local IP address and port, when provided or if one had been
1894 if ( !local
&& m_localAddress
.GetAddress().IsOk() )
1895 local
= &m_localAddress
;
1898 m_impl
->SetLocal(local
->GetAddress());
1900 m_impl
->SetInitialSocketBuffers(m_initialRecvBufferSize
, m_initialSendBufferSize
);
1902 m_impl
->SetPeer(remote
.GetAddress());
1904 // Finally do create the socket and connect to the peer
1905 const wxSocketError err
= m_impl
->CreateClient(wait
);
1907 if ( err
!= wxSOCKET_NOERROR
)
1909 if ( err
== wxSOCKET_WOULDBLOCK
)
1911 wxASSERT_MSG( !wait
, "shouldn't get this for blocking connect" );
1913 m_establishing
= true;
1923 bool wxSocketClient::Connect(const wxSockAddress
& remote
, bool wait
)
1925 return DoConnect(remote
, NULL
, wait
);
1928 bool wxSocketClient::Connect(const wxSockAddress
& remote
,
1929 const wxSockAddress
& local
,
1932 return DoConnect(remote
, &local
, wait
);
1935 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
)
1939 // this happens if the initial attempt to connect succeeded without
1944 wxCHECK_MSG( m_establishing
&& m_impl
, false,
1945 "No connection establishment attempt in progress" );
1947 // notice that we return true even if DoWait() returned -1, i.e. if an
1948 // error occurred and connection was lost: this is intentional as we should
1949 // return false only if timeout expired without anything happening
1950 return DoWait(seconds
, milliseconds
, wxSOCKET_CONNECTION_FLAG
) != 0;
1953 // ==========================================================================
1955 // ==========================================================================
1957 wxDatagramSocket::wxDatagramSocket( const wxSockAddress
& addr
,
1958 wxSocketFlags flags
)
1959 : wxSocketBase( flags
, wxSOCKET_DATAGRAM
)
1961 // Create the socket
1962 m_impl
= wxSocketImpl::Create(*this);
1967 // Setup the socket as non connection oriented
1968 m_impl
->SetLocal(addr
.GetAddress());
1969 if (flags
& wxSOCKET_REUSEADDR
)
1971 m_impl
->SetReusable();
1973 if (GetFlags() & wxSOCKET_BROADCAST
)
1975 m_impl
->SetBroadcast();
1977 if (GetFlags() & wxSOCKET_NOBIND
)
1979 m_impl
->DontDoBind();
1982 if ( m_impl
->CreateUDP() != wxSOCKET_NOERROR
)
1989 // Initialize all stuff
1990 m_connected
= false;
1991 m_establishing
= false;
1994 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
,
2003 wxDatagramSocket
& wxDatagramSocket::SendTo( const wxSockAddress
& addr
,
2007 wxASSERT_MSG( m_impl
, _T("Socket not initialised") );
2009 m_impl
->SetPeer(addr
.GetAddress());
2014 // ==========================================================================
2016 // ==========================================================================
2018 class wxSocketModule
: public wxModule
2021 virtual bool OnInit()
2023 // wxSocketBase will call Initialize() itself only if sockets are
2024 // really used, don't do it from here
2028 virtual void OnExit()
2030 if ( wxSocketBase::IsInitialized() )
2031 wxSocketBase::Shutdown();
2035 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
2038 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)
2040 #if defined(wxUSE_SELECT_DISPATCHER) && wxUSE_SELECT_DISPATCHER
2041 // NOTE: we need to force linking against socketiohandler.cpp otherwise in
2042 // static builds of wxWidgets the ManagerSetter::ManagerSetter ctor
2043 // contained there wouldn't be ever called
2044 wxFORCE_LINK_MODULE( socketiohandler
)
2047 #endif // wxUSE_SOCKETS