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
9 // Licence: 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"
46 #include "wx/private/fd.h"
47 #include "wx/private/socket.h"
53 // we use MSG_NOSIGNAL to avoid getting SIGPIPE when sending data to a remote
54 // host which closed the connection if it is available, otherwise we rely on
55 // SO_NOSIGPIPE existency
57 // this should cover all the current Unix systems (Windows never sends any
58 // signals anyhow) but if we find one that has neither we should explicitly
59 // ignore SIGPIPE for it
60 // OpenVMS has neither MSG_NOSIGNAL nor SO_NOSIGPIPE. However the socket sample
61 // seems to work. Not sure if problems will show up on OpenVMS using sockets.
63 #define wxSOCKET_MSG_NOSIGNAL MSG_NOSIGNAL
64 #else // MSG_NOSIGNAL not available (BSD including OS X)
65 // next best possibility is to use SO_NOSIGPIPE socket option, this covers
66 // BSD systems (including OS X) -- but if we don't have it neither (AIX and
67 // old HP-UX do not), we have to fall back to the old way of simply
68 // disabling SIGPIPE temporarily, so define a class to do it in a safe way
69 #if defined(__UNIX__) && !defined(SO_NOSIGPIPE)
70 extern "C" { typedef void (*wxSigHandler_t
)(int); }
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 wxSigHandler_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 wxT("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 // We can be passed only wxSOCKET_WAITALL{_READ,_WRITE} or
175 // wxSOCKET_NOWAIT{_READ,_WRITE} normally.
176 wxASSERT_MSG( !(flag
& wxSOCKET_WAITALL
) || !(flag
& wxSOCKET_NOWAIT
),
179 // preserve wxSOCKET_BLOCK value when switching to wxSOCKET_WAITALL
180 // mode but not when switching to wxSOCKET_NOWAIT as the latter is
181 // incompatible with wxSOCKET_BLOCK
182 if ( flag
!= wxSOCKET_NOWAIT
)
183 flag
|= m_oldflags
& wxSOCKET_BLOCK
;
185 socket
->SetFlags(flag
);
188 ~wxSocketWaitModeChanger()
190 m_socket
->SetFlags(m_oldflags
);
194 wxSocketBase
* const m_socket
;
195 const int m_oldflags
;
197 wxDECLARE_NO_COPY_CLASS(wxSocketWaitModeChanger
);
200 // wxSocketRead/WriteGuard are instantiated before starting reading
201 // from/writing to the socket
202 class wxSocketReadGuard
205 wxSocketReadGuard(wxSocketBase
*socket
)
208 wxASSERT_MSG( !m_socket
->m_reading
, "read reentrancy?" );
210 m_socket
->m_reading
= true;
215 m_socket
->m_reading
= false;
217 // connection could have been lost while reading, in this case calling
218 // ReenableEvents() would assert and is not necessary anyhow
219 wxSocketImpl
* const impl
= m_socket
->m_impl
;
220 if ( impl
&& impl
->m_fd
!= INVALID_SOCKET
)
221 impl
->ReenableEvents(wxSOCKET_INPUT_FLAG
);
225 wxSocketBase
* const m_socket
;
227 wxDECLARE_NO_COPY_CLASS(wxSocketReadGuard
);
230 class wxSocketWriteGuard
233 wxSocketWriteGuard(wxSocketBase
*socket
)
236 wxASSERT_MSG( !m_socket
->m_writing
, "write reentrancy?" );
238 m_socket
->m_writing
= true;
241 ~wxSocketWriteGuard()
243 m_socket
->m_writing
= false;
245 wxSocketImpl
* const impl
= m_socket
->m_impl
;
246 if ( impl
&& impl
->m_fd
!= INVALID_SOCKET
)
247 impl
->ReenableEvents(wxSOCKET_OUTPUT_FLAG
);
251 wxSocketBase
* const m_socket
;
253 wxDECLARE_NO_COPY_CLASS(wxSocketWriteGuard
);
256 // ============================================================================
258 // ============================================================================
260 wxSocketManager
*wxSocketManager::ms_manager
= NULL
;
263 void wxSocketManager::Set(wxSocketManager
*manager
)
265 wxASSERT_MSG( !ms_manager
, "too late to set manager now" );
267 ms_manager
= manager
;
271 void wxSocketManager::Init()
273 wxASSERT_MSG( !ms_manager
, "shouldn't be initialized twice" );
276 Details: Initialize() creates a hidden window as a sink for socket
277 events, such as 'read completed'. wxMSW has only one message loop
278 for the main thread. If Initialize is called in a secondary thread,
279 the socket window will be created for the secondary thread, but
280 since there is no message loop on this thread, it will never
281 receive events and all socket operations will time out.
282 BTW, the main thread must not be stopped using sleep or block
283 on a semaphore (a bad idea in any case) or socket operations
286 On the Mac side, Initialize() stores a pointer to the CFRunLoop for
287 the main thread. Because secondary threads do not have run loops,
288 adding event notifications to the "Current" loop would have no
289 effect at all, events would never fire.
291 wxASSERT_MSG( wxIsMainThread(),
292 "sockets must be initialized from the main thread" );
294 wxAppConsole
* const app
= wxAppConsole::GetInstance();
295 wxCHECK_RET( app
, "sockets can't be initialized without wxApp" );
297 ms_manager
= app
->GetTraits()->GetSocketManager();
300 // ==========================================================================
302 // ==========================================================================
304 wxSocketImpl::wxSocketImpl(wxSocketBase
& wxsocket
)
305 : m_wxsocket(&wxsocket
)
307 m_fd
= INVALID_SOCKET
;
308 m_error
= wxSOCKET_NOERROR
;
312 SetTimeout(wxsocket
.GetTimeout() * 1000);
314 m_establishing
= false;
318 m_initialRecvBufferSize
= -1;
319 m_initialSendBufferSize
= -1;
322 wxSocketImpl::~wxSocketImpl()
324 if ( m_fd
!= INVALID_SOCKET
)
328 bool wxSocketImpl::PreCreateCheck(const wxSockAddressImpl
& addr
)
330 if ( m_fd
!= INVALID_SOCKET
)
332 m_error
= wxSOCKET_INVSOCK
;
338 m_error
= wxSOCKET_INVADDR
;
345 void wxSocketImpl::PostCreation()
347 // FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option
349 EnableSocketOption(SO_NOSIGPIPE
);
353 EnableSocketOption(SO_REUSEADDR
);
357 wxASSERT_MSG( !m_stream
, "broadcasting is for datagram sockets only" );
359 EnableSocketOption(SO_BROADCAST
);
362 if ( m_initialRecvBufferSize
>= 0 )
363 SetSocketOption(SO_RCVBUF
, m_initialRecvBufferSize
);
364 if ( m_initialSendBufferSize
>= 0 )
365 SetSocketOption(SO_SNDBUF
, m_initialSendBufferSize
);
367 // we always put our sockets in unblocked mode and handle blocking
368 // ourselves in DoRead/Write() if wxSOCKET_WAITALL is specified
369 UnblockAndRegisterWithEventLoop();
372 wxSocketError
wxSocketImpl::UpdateLocalAddress()
374 if ( !m_local
.IsOk() )
376 // ensure that we have a valid object using the correct family: correct
377 // being the same one as our peer uses as we have no other way to
379 m_local
.Create(m_peer
.GetFamily());
382 WX_SOCKLEN_T lenAddr
= m_local
.GetLen();
383 if ( getsockname(m_fd
, m_local
.GetWritableAddr(), &lenAddr
) != 0 )
386 m_error
= wxSOCKET_IOERR
;
390 return wxSOCKET_NOERROR
;
393 wxSocketError
wxSocketImpl::CreateServer()
395 if ( !PreCreateCheck(m_local
) )
401 // do create the socket
402 m_fd
= socket(m_local
.GetFamily(), SOCK_STREAM
, 0);
404 if ( m_fd
== INVALID_SOCKET
)
406 m_error
= wxSOCKET_IOERR
;
407 return wxSOCKET_IOERR
;
412 // and then bind to and listen on it
414 // FIXME: should we test for m_dobind here?
415 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
416 m_error
= wxSOCKET_IOERR
;
420 if ( listen(m_fd
, 5) != 0 )
421 m_error
= wxSOCKET_IOERR
;
430 // finally retrieve the address we effectively bound to
431 return UpdateLocalAddress();
434 wxSocketError
wxSocketImpl::CreateClient(bool wait
)
436 if ( !PreCreateCheck(m_peer
) )
439 m_fd
= socket(m_peer
.GetFamily(), SOCK_STREAM
, 0);
441 if ( m_fd
== INVALID_SOCKET
)
443 m_error
= wxSOCKET_IOERR
;
444 return wxSOCKET_IOERR
;
449 // If a local address has been set, then bind to it before calling connect
450 if ( m_local
.IsOk() )
452 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
455 m_error
= wxSOCKET_IOERR
;
461 int rc
= connect(m_fd
, m_peer
.GetAddr(), m_peer
.GetLen());
462 if ( rc
== SOCKET_ERROR
)
464 wxSocketError err
= GetLastError();
465 if ( err
== wxSOCKET_WOULDBLOCK
)
467 m_establishing
= true;
469 // block waiting for connection if we should (otherwise just return
470 // wxSOCKET_WOULDBLOCK to the caller)
473 err
= SelectWithTimeout(wxSOCKET_CONNECTION_FLAG
)
476 m_establishing
= false;
484 m_error
= wxSOCKET_NOERROR
;
491 wxSocketError
wxSocketImpl::CreateUDP()
493 if ( !PreCreateCheck(m_local
) )
499 m_fd
= socket(m_local
.GetFamily(), SOCK_DGRAM
, 0);
501 if ( m_fd
== INVALID_SOCKET
)
503 m_error
= wxSOCKET_IOERR
;
504 return wxSOCKET_IOERR
;
511 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
514 m_error
= wxSOCKET_IOERR
;
518 return UpdateLocalAddress();
521 return wxSOCKET_NOERROR
;
524 wxSocketImpl
*wxSocketImpl::Accept(wxSocketBase
& wxsocket
)
526 wxSockAddressStorage from
;
527 WX_SOCKLEN_T fromlen
= sizeof(from
);
528 const wxSOCKET_T fd
= accept(m_fd
, &from
.addr
, &fromlen
);
530 // accepting is similar to reading in the sense that it resets "ready for
531 // read" flag on the socket
532 ReenableEvents(wxSOCKET_INPUT_FLAG
);
534 if ( fd
== INVALID_SOCKET
)
537 wxSocketManager
* const manager
= wxSocketManager::Get();
541 wxSocketImpl
* const sock
= manager
->CreateSocket(wxsocket
);
546 sock
->m_peer
= wxSockAddressImpl(from
.addr
, fromlen
);
548 sock
->UnblockAndRegisterWithEventLoop();
554 void wxSocketImpl::Close()
556 if ( m_fd
!= INVALID_SOCKET
)
559 m_fd
= INVALID_SOCKET
;
563 void wxSocketImpl::Shutdown()
565 if ( m_fd
!= INVALID_SOCKET
)
567 shutdown(m_fd
, 1 /* SD_SEND */);
573 * Sets the timeout for blocking calls. Time is expressed in
576 void wxSocketImpl::SetTimeout(unsigned long millis
)
578 SetTimeValFromMS(m_timeout
, millis
);
581 void wxSocketImpl::NotifyOnStateChange(wxSocketNotify event
)
583 m_wxsocket
->OnRequest(event
);
586 /* Address handling */
587 wxSocketError
wxSocketImpl::SetLocal(const wxSockAddressImpl
& local
)
589 /* the socket must be initialized, or it must be a server */
590 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
592 m_error
= wxSOCKET_INVSOCK
;
593 return wxSOCKET_INVSOCK
;
598 m_error
= wxSOCKET_INVADDR
;
599 return wxSOCKET_INVADDR
;
604 return wxSOCKET_NOERROR
;
607 wxSocketError
wxSocketImpl::SetPeer(const wxSockAddressImpl
& peer
)
611 m_error
= wxSOCKET_INVADDR
;
612 return wxSOCKET_INVADDR
;
617 return wxSOCKET_NOERROR
;
620 const wxSockAddressImpl
& wxSocketImpl::GetLocal()
622 if ( !m_local
.IsOk() )
623 UpdateLocalAddress();
628 // ----------------------------------------------------------------------------
630 // ----------------------------------------------------------------------------
632 // this macro wraps the given expression (normally a syscall) in a loop which
633 // ignores any interruptions, i.e. reevaluates it again if it failed and errno
636 #define DO_WHILE_EINTR( rc, syscall ) \
640 while ( rc == -1 && errno == EINTR )
642 #define DO_WHILE_EINTR( rc, syscall ) rc = (syscall)
645 int wxSocketImpl::RecvStream(void *buffer
, int size
)
648 DO_WHILE_EINTR( ret
, recv(m_fd
, static_cast<char *>(buffer
), size
, 0) );
652 // receiving 0 bytes for a TCP socket indicates that the connection was
653 // closed by peer so shut down our end as well (for UDP sockets empty
654 // datagrams are also possible)
655 m_establishing
= false;
656 NotifyOnStateChange(wxSOCKET_LOST
);
660 // do not return an error in this case however
666 int wxSocketImpl::SendStream(const void *buffer
, int size
)
668 #ifdef wxNEEDS_IGNORE_SIGPIPE
669 IgnoreSignal
ignore(SIGPIPE
);
673 DO_WHILE_EINTR( ret
, send(m_fd
, static_cast<const char *>(buffer
), size
,
674 wxSOCKET_MSG_NOSIGNAL
) );
679 int wxSocketImpl::RecvDgram(void *buffer
, int size
)
681 wxSockAddressStorage from
;
682 WX_SOCKLEN_T fromlen
= sizeof(from
);
685 DO_WHILE_EINTR( ret
, recvfrom(m_fd
, static_cast<char *>(buffer
), size
,
686 0, &from
.addr
, &fromlen
) );
688 if ( ret
== SOCKET_ERROR
)
691 m_peer
= wxSockAddressImpl(from
.addr
, fromlen
);
692 if ( !m_peer
.IsOk() )
698 int wxSocketImpl::SendDgram(const void *buffer
, int size
)
700 if ( !m_peer
.IsOk() )
702 m_error
= wxSOCKET_INVADDR
;
707 DO_WHILE_EINTR( ret
, sendto(m_fd
, static_cast<const char *>(buffer
), size
,
708 0, m_peer
.GetAddr(), m_peer
.GetLen()) );
713 int wxSocketImpl::Read(void *buffer
, int size
)
715 // server sockets can't be used for IO, only to accept new connections
716 if ( m_fd
== INVALID_SOCKET
|| m_server
)
718 m_error
= wxSOCKET_INVSOCK
;
722 int ret
= m_stream
? RecvStream(buffer
, size
)
723 : RecvDgram(buffer
, size
);
725 m_error
= ret
== SOCKET_ERROR
? GetLastError() : wxSOCKET_NOERROR
;
730 int wxSocketImpl::Write(const void *buffer
, int size
)
732 if ( m_fd
== INVALID_SOCKET
|| m_server
)
734 m_error
= wxSOCKET_INVSOCK
;
738 int ret
= m_stream
? SendStream(buffer
, size
)
739 : SendDgram(buffer
, size
);
741 m_error
= ret
== SOCKET_ERROR
? GetLastError() : wxSOCKET_NOERROR
;
746 // ==========================================================================
748 // ==========================================================================
750 // --------------------------------------------------------------------------
751 // Initialization and shutdown
752 // --------------------------------------------------------------------------
757 // counts the number of calls to Initialize() minus the number of calls to
758 // Shutdown(): we don't really need it any more but it was documented that
759 // Shutdown() must be called the same number of times as Initialize() and using
760 // a counter helps us to check it
761 int gs_socketInitCount
= 0;
763 } // anonymous namespace
765 bool wxSocketBase::IsInitialized()
767 wxASSERT_MSG( wxIsMainThread(), "unsafe to call from other threads" );
769 return gs_socketInitCount
!= 0;
772 bool wxSocketBase::Initialize()
774 wxCHECK_MSG( wxIsMainThread(), false,
775 "must be called from the main thread" );
777 if ( !gs_socketInitCount
)
779 wxSocketManager
* const manager
= wxSocketManager::Get();
780 if ( !manager
|| !manager
->OnInit() )
784 gs_socketInitCount
++;
789 void wxSocketBase::Shutdown()
791 wxCHECK_RET( wxIsMainThread(), "must be called from the main thread" );
793 wxCHECK_RET( gs_socketInitCount
> 0, "too many calls to Shutdown()" );
795 if ( !--gs_socketInitCount
)
797 wxSocketManager
* const manager
= wxSocketManager::Get();
798 wxCHECK_RET( manager
, "should have a socket manager" );
804 // --------------------------------------------------------------------------
806 // --------------------------------------------------------------------------
808 void wxSocketBase::Init()
811 m_type
= wxSOCKET_UNINIT
;
824 m_beingDeleted
= false;
839 // when we create the first socket in the main thread we initialize the
840 // OS-dependent socket stuff: notice that this means that the user code
841 // needs to call wxSocket::Initialize() itself if the first socket it
842 // creates is not created in the main thread
843 if ( wxIsMainThread() )
847 wxLogError(_("Cannot initialize sockets"));
852 wxSocketBase::wxSocketBase()
857 wxSocketBase::wxSocketBase(wxSocketFlags flags
, wxSocketType type
)
866 wxSocketBase::~wxSocketBase()
868 // Shutdown and close the socket
872 // Destroy the implementation object
875 // Free the pushback buffer
879 bool wxSocketBase::Destroy()
881 // Delayed destruction: the socket will be deleted during the next idle
882 // loop iteration. This ensures that all pending events have been
884 m_beingDeleted
= true;
886 // Shutdown and close the socket
889 // Suppress events from now on
892 // Schedule this object for deletion instead of destroying it right now if
893 // it can have other events pending for it and we have a way to do it.
895 // Notice that sockets used in other threads won't have any events for them
896 // and we shouldn't use delayed destruction mechanism for them as it's not
898 if ( wxIsMainThread() && wxTheApp
)
900 wxTheApp
->ScheduleForDestruction(this);
904 // in wxBase we might have no app object at all, don't leak memory
911 // ----------------------------------------------------------------------------
913 // ----------------------------------------------------------------------------
915 void wxSocketBase::SetError(wxSocketError error
)
917 m_impl
->m_error
= error
;
920 wxSocketError
wxSocketBase::LastError() const
922 return m_impl
->GetError();
925 // --------------------------------------------------------------------------
927 // --------------------------------------------------------------------------
929 // The following IO operations update m_lcount:
930 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
931 bool wxSocketBase::Close()
933 // Interrupt pending waits
939 m_establishing
= false;
943 void wxSocketBase::ShutdownOutput()
949 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
)
951 wxSocketReadGuard
read(this);
953 m_lcount_read
= DoRead(buffer
, nbytes
);
954 m_lcount
= m_lcount_read
;
959 wxUint32
wxSocketBase::DoRead(void* buffer_
, wxUint32 nbytes
)
961 wxCHECK_MSG( m_impl
, 0, "socket must be valid" );
963 // We use pointer arithmetic here which doesn't work with void pointers.
964 char *buffer
= static_cast<char *>(buffer_
);
965 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
967 // Try the push back buffer first, even before checking whether the socket
968 // is valid to allow reading previously pushed back data from an already
970 wxUint32 total
= GetPushback(buffer
, nbytes
, false);
976 // our socket is non-blocking so Read() will return immediately if
977 // there is nothing to read yet and it's more efficient to try it first
978 // before entering DoWait() which is going to start dispatching GUI
979 // events and, even more importantly, we must do this under Windows
980 // where we're not going to get notifications about socket being ready
981 // for reading before we read all the existing data from it
982 const int ret
= !m_impl
->m_stream
|| m_connected
983 ? m_impl
->Read(buffer
, nbytes
)
987 if ( m_impl
->GetLastError() == wxSOCKET_WOULDBLOCK
)
989 // if we don't want to wait, just return immediately
990 if ( m_flags
& wxSOCKET_NOWAIT_READ
)
992 // this shouldn't be counted as an error in this case
993 SetError(wxSOCKET_NOERROR
);
997 // otherwise wait until the socket becomes ready for reading or
998 // an error occurs on it
999 if ( !DoWaitWithTimeout(wxSOCKET_INPUT_FLAG
) )
1001 // and exit if the timeout elapsed before it did
1002 SetError(wxSOCKET_TIMEDOUT
);
1009 else // "real" error
1011 SetError(wxSOCKET_IOERR
);
1015 else if ( ret
== 0 )
1017 // for connection-oriented (e.g. TCP) sockets we can only read
1018 // 0 bytes if the other end has been closed, and for connectionless
1019 // ones (UDP) this flag doesn't make sense anyhow so we can set it
1020 // to true too without doing any harm
1023 // we're not going to read anything else and so if we haven't read
1024 // anything (or not everything in wxSOCKET_WAITALL case) already,
1026 if ( (m_flags
& wxSOCKET_WAITALL_READ
) || !total
)
1027 SetError(wxSOCKET_IOERR
);
1033 // if we are happy to read something and not the entire nbytes bytes,
1035 if ( !(m_flags
& wxSOCKET_WAITALL_READ
) )
1045 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
)
1049 unsigned char sig
[4];
1050 unsigned char len
[4];
1053 wxSocketReadGuard
read(this);
1055 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_WAITALL_READ
);
1058 if ( DoRead(&msg
, sizeof(msg
)) == sizeof(msg
) )
1060 wxUint32 sig
= (wxUint32
)msg
.sig
[0];
1061 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
1062 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
1063 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
1065 if ( sig
== 0xfeeddead )
1067 wxUint32 len
= (wxUint32
)msg
.len
[0];
1068 len
|= (wxUint32
)(msg
.len
[1] << 8);
1069 len
|= (wxUint32
)(msg
.len
[2] << 16);
1070 len
|= (wxUint32
)(msg
.len
[3] << 24);
1075 len2
= len
- nbytes
;
1081 // Don't attempt to read if the msg was zero bytes long.
1082 m_lcount_read
= len
? DoRead(buffer
, len
) : 0;
1083 m_lcount
= m_lcount_read
;
1087 char discard_buffer
[MAX_DISCARD_SIZE
];
1090 // NOTE: discarded bytes don't add to m_lcount.
1093 discard_len
= len2
> MAX_DISCARD_SIZE
1096 discard_len
= DoRead(discard_buffer
, (wxUint32
)discard_len
);
1097 len2
-= (wxUint32
)discard_len
;
1099 while ((discard_len
> 0) && len2
);
1102 if ( !len2
&& DoRead(&msg
, sizeof(msg
)) == sizeof(msg
) )
1104 sig
= (wxUint32
)msg
.sig
[0];
1105 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
1106 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
1107 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
1109 if ( sig
== 0xdeadfeed )
1116 SetError(wxSOCKET_IOERR
);
1121 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
)
1123 wxSocketReadGuard
read(this);
1125 // Peek() should never block
1126 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_NOWAIT
);
1128 m_lcount
= DoRead(buffer
, nbytes
);
1130 Pushback(buffer
, m_lcount
);
1135 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
)
1137 wxSocketWriteGuard
write(this);
1139 m_lcount_write
= DoWrite(buffer
, nbytes
);
1140 m_lcount
= m_lcount_write
;
1145 // This function is a mirror image of DoRead() except that it doesn't use the
1146 // push back buffer and doesn't treat 0 return value specially (normally this
1147 // shouldn't happen at all here), so please see comments there for explanations
1148 wxUint32
wxSocketBase::DoWrite(const void *buffer_
, wxUint32 nbytes
)
1150 wxCHECK_MSG( m_impl
, 0, "socket must be valid" );
1152 const char *buffer
= static_cast<const char *>(buffer_
);
1153 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1158 if ( m_impl
->m_stream
&& !m_connected
)
1160 if ( (m_flags
& wxSOCKET_WAITALL_WRITE
) || !total
)
1161 SetError(wxSOCKET_IOERR
);
1165 const int ret
= m_impl
->Write(buffer
, nbytes
);
1168 if ( m_impl
->GetLastError() == wxSOCKET_WOULDBLOCK
)
1170 if ( m_flags
& wxSOCKET_NOWAIT_WRITE
)
1173 if ( !DoWaitWithTimeout(wxSOCKET_OUTPUT_FLAG
) )
1175 SetError(wxSOCKET_TIMEDOUT
);
1181 else // "real" error
1183 SetError(wxSOCKET_IOERR
);
1190 if ( !(m_flags
& wxSOCKET_WAITALL_WRITE
) )
1200 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
)
1204 unsigned char sig
[4];
1205 unsigned char len
[4];
1208 wxSocketWriteGuard
write(this);
1210 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_WAITALL_WRITE
);
1212 msg
.sig
[0] = (unsigned char) 0xad;
1213 msg
.sig
[1] = (unsigned char) 0xde;
1214 msg
.sig
[2] = (unsigned char) 0xed;
1215 msg
.sig
[3] = (unsigned char) 0xfe;
1217 msg
.len
[0] = (unsigned char) (nbytes
& 0xff);
1218 msg
.len
[1] = (unsigned char) ((nbytes
>> 8) & 0xff);
1219 msg
.len
[2] = (unsigned char) ((nbytes
>> 16) & 0xff);
1220 msg
.len
[3] = (unsigned char) ((nbytes
>> 24) & 0xff);
1223 if ( DoWrite(&msg
, sizeof(msg
)) == sizeof(msg
) )
1225 m_lcount_write
= DoWrite(buffer
, nbytes
);
1226 m_lcount
= m_lcount_write
;
1227 if ( m_lcount_write
== nbytes
)
1229 msg
.sig
[0] = (unsigned char) 0xed;
1230 msg
.sig
[1] = (unsigned char) 0xfe;
1231 msg
.sig
[2] = (unsigned char) 0xad;
1232 msg
.sig
[3] = (unsigned char) 0xde;
1236 msg
.len
[3] = (char) 0;
1238 if ( DoWrite(&msg
, sizeof(msg
)) == sizeof(msg
))
1244 SetError(wxSOCKET_IOERR
);
1249 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
)
1252 Pushback(buffer
, nbytes
);
1254 SetError(wxSOCKET_NOERROR
);
1260 wxSocketBase
& wxSocketBase::Discard()
1262 char *buffer
= new char[MAX_DISCARD_SIZE
];
1266 wxSocketReadGuard
read(this);
1268 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_NOWAIT
);
1272 ret
= DoRead(buffer
, MAX_DISCARD_SIZE
);
1275 while (ret
== MAX_DISCARD_SIZE
);
1279 SetError(wxSOCKET_NOERROR
);
1284 // --------------------------------------------------------------------------
1286 // --------------------------------------------------------------------------
1289 This function will check for the events specified in the flags parameter,
1290 and it will return a mask indicating which operations can be performed.
1292 wxSocketEventFlags
wxSocketImpl::Select(wxSocketEventFlags flags
,
1293 const timeval
*timeout
)
1295 if ( m_fd
== INVALID_SOCKET
)
1296 return (wxSOCKET_LOST_FLAG
& flags
);
1302 tv
.tv_sec
= tv
.tv_usec
= 0;
1304 // prepare the FD sets, passing NULL for the one(s) we don't use
1306 readfds
, *preadfds
= NULL
,
1307 writefds
, *pwritefds
= NULL
,
1308 exceptfds
; // always want to know about errors
1310 if ( flags
& wxSOCKET_INPUT_FLAG
)
1311 preadfds
= &readfds
;
1313 if ( flags
& wxSOCKET_OUTPUT_FLAG
)
1314 pwritefds
= &writefds
;
1316 // When using non-blocking connect() the client socket becomes connected
1317 // (successfully or not) when it becomes writable but when using
1318 // non-blocking accept() the server socket becomes connected when it
1319 // becomes readable.
1320 if ( flags
& wxSOCKET_CONNECTION_FLAG
)
1323 preadfds
= &readfds
;
1325 pwritefds
= &writefds
;
1330 wxFD_ZERO(preadfds
);
1331 wxFD_SET(m_fd
, preadfds
);
1336 wxFD_ZERO(pwritefds
);
1337 wxFD_SET(m_fd
, pwritefds
);
1340 wxFD_ZERO(&exceptfds
);
1341 wxFD_SET(m_fd
, &exceptfds
);
1343 const int rc
= select(m_fd
+ 1, preadfds
, pwritefds
, &exceptfds
, &tv
);
1345 // check for errors first
1346 if ( rc
== -1 || wxFD_ISSET(m_fd
, &exceptfds
) )
1348 m_establishing
= false;
1350 return wxSOCKET_LOST_FLAG
& flags
;
1356 wxASSERT_MSG( rc
== 1, "unexpected select() return value" );
1358 wxSocketEventFlags detected
= 0;
1359 if ( preadfds
&& wxFD_ISSET(m_fd
, preadfds
) )
1360 detected
|= wxSOCKET_INPUT_FLAG
;
1362 if ( pwritefds
&& wxFD_ISSET(m_fd
, pwritefds
) )
1364 // check for the case of non-blocking connect()
1365 if ( m_establishing
&& !m_server
)
1368 SOCKOPTLEN_T len
= sizeof(error
);
1369 m_establishing
= false;
1370 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1373 detected
= wxSOCKET_LOST_FLAG
;
1375 detected
|= wxSOCKET_CONNECTION_FLAG
;
1377 else // not called to get non-blocking connect() status
1379 detected
|= wxSOCKET_OUTPUT_FLAG
;
1383 return detected
& flags
;
1387 wxSocketBase::DoWait(long seconds
, long milliseconds
, wxSocketEventFlags flags
)
1389 // Use either the provided timeout or the default timeout value associated
1390 // with this socket.
1392 // TODO: allow waiting forever, see #9443
1393 const long timeout
= seconds
== -1 ? m_timeout
* 1000
1394 : seconds
* 1000 + milliseconds
;
1396 return DoWait(timeout
, flags
);
1400 wxSocketBase::DoWait(long timeout
, wxSocketEventFlags flags
)
1402 wxCHECK_MSG( m_impl
, -1, "can't wait on invalid socket" );
1404 // we're never going to become ready in a TCP client if we're not connected
1405 // any more (OTOH a server can call this to precisely wait for a connection
1406 // so do wait for it in this case and UDP client is never "connected")
1407 if ( !m_impl
->IsServer() &&
1408 m_impl
->m_stream
&& !m_connected
&& !m_establishing
)
1411 // This can be set to true from Interrupt() to exit this function a.s.a.p.
1412 m_interrupt
= false;
1415 const wxMilliClock_t timeEnd
= wxGetLocalTimeMillis() + timeout
;
1417 // Get the active event loop which we'll use for the message dispatching
1418 // when running in the main thread unless this was explicitly disabled by
1419 // setting wxSOCKET_BLOCK flag
1420 wxEventLoopBase
*eventLoop
;
1421 if ( !(m_flags
& wxSOCKET_BLOCK
) && wxIsMainThread() )
1423 eventLoop
= wxEventLoop::GetActive();
1425 else // in worker thread
1427 // We never dispatch messages from threads other than the main one.
1431 // Make sure the events we're interested in are enabled before waiting for
1432 // them: this is really necessary here as otherwise this could happen:
1433 // 1. DoRead(wxSOCKET_WAITALL) is called
1434 // 2. There is nothing to read so DoWait(wxSOCKET_INPUT_FLAG) is called
1435 // 3. Some, but not all data appears, wxSocketImplUnix::OnReadWaiting()
1436 // is called and wxSOCKET_INPUT_FLAG events are disabled in it
1437 // 4. Because of wxSOCKET_WAITALL we call DoWait() again but the events
1438 // are still disabled and we block forever
1440 // More elegant solution would be nice but for now simply re-enabling the
1441 // events here will do
1442 m_impl
->ReenableEvents(flags
& (wxSOCKET_INPUT_FLAG
| wxSOCKET_OUTPUT_FLAG
));
1445 // Wait until we receive the event we're waiting for or the timeout expires
1446 // (but note that we always execute the loop at least once, even if timeout
1447 // is 0 as this is used for polling)
1449 for ( bool firstTime
= true; !m_interrupt
; firstTime
= false )
1451 long timeLeft
= wxMilliClockToLong(timeEnd
- wxGetLocalTimeMillis());
1460 wxSocketEventFlags events
;
1463 // reset them before starting to wait
1466 eventLoop
->DispatchTimeout(timeLeft
);
1468 events
= m_eventsgot
;
1470 else // no event loop or waiting in another thread
1472 // as explained below, we should always check for wxSOCKET_LOST_FLAG
1474 SetTimeValFromMS(tv
, timeLeft
);
1475 events
= m_impl
->Select(flags
| wxSOCKET_LOST_FLAG
, &tv
);
1478 // always check for wxSOCKET_LOST_FLAG, even if flags doesn't include
1479 // it, as continuing to wait for anything else after getting it is
1481 if ( events
& wxSOCKET_LOST_FLAG
)
1483 m_connected
= false;
1484 m_establishing
= false;
1489 // otherwise mask out the bits we're not interested in
1492 // Incoming connection (server) or connection established (client)?
1493 if ( events
& wxSOCKET_CONNECTION_FLAG
)
1496 m_establishing
= false;
1501 // Data available or output buffer ready?
1502 if ( (events
& wxSOCKET_INPUT_FLAG
) || (events
& wxSOCKET_OUTPUT_FLAG
) )
1512 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
1514 return DoWait(seconds
, milliseconds
,
1515 wxSOCKET_INPUT_FLAG
|
1516 wxSOCKET_OUTPUT_FLAG
|
1517 wxSOCKET_CONNECTION_FLAG
) != 0;
1520 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
1522 // Check pushback buffer before entering DoWait
1526 // Check if the socket is not already ready for input, if it is, there is
1527 // no need to start waiting for it (worse, we'll actually never get a
1528 // notification about the socket becoming ready if it is already under
1530 if ( m_impl
->Select(wxSOCKET_INPUT_FLAG
) )
1533 return DoWait(seconds
, milliseconds
, wxSOCKET_INPUT_FLAG
) != 0;
1537 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
1539 if ( m_impl
->Select(wxSOCKET_OUTPUT_FLAG
) )
1542 return DoWait(seconds
, milliseconds
, wxSOCKET_OUTPUT_FLAG
) != 0;
1545 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
1547 return DoWait(seconds
, milliseconds
, wxSOCKET_LOST_FLAG
) == -1;
1550 // --------------------------------------------------------------------------
1552 // --------------------------------------------------------------------------
1555 // Get local or peer address
1558 bool wxSocketBase::GetPeer(wxSockAddress
& addr
) const
1560 wxCHECK_MSG( m_impl
, false, "invalid socket" );
1562 const wxSockAddressImpl
& peer
= m_impl
->GetPeer();
1566 addr
.SetAddress(peer
);
1571 bool wxSocketBase::GetLocal(wxSockAddress
& addr
) const
1573 wxCHECK_MSG( m_impl
, false, "invalid socket" );
1575 const wxSockAddressImpl
& local
= m_impl
->GetLocal();
1576 if ( !local
.IsOk() )
1579 addr
.SetAddress(local
);
1585 // Save and restore socket state
1588 void wxSocketBase::SaveState()
1590 wxSocketState
*state
;
1592 state
= new wxSocketState();
1594 state
->m_flags
= m_flags
;
1595 state
->m_notify
= m_notify
;
1596 state
->m_eventmask
= m_eventmask
;
1597 state
->m_clientData
= m_clientData
;
1599 m_states
.Append(state
);
1602 void wxSocketBase::RestoreState()
1604 wxList::compatibility_iterator node
;
1605 wxSocketState
*state
;
1607 node
= m_states
.GetLast();
1611 state
= (wxSocketState
*)node
->GetData();
1613 m_flags
= state
->m_flags
;
1614 m_notify
= state
->m_notify
;
1615 m_eventmask
= state
->m_eventmask
;
1616 m_clientData
= state
->m_clientData
;
1618 m_states
.Erase(node
);
1623 // Timeout and flags
1626 void wxSocketBase::SetTimeout(long seconds
)
1628 m_timeout
= seconds
;
1631 m_impl
->SetTimeout(m_timeout
* 1000);
1634 void wxSocketBase::SetFlags(wxSocketFlags flags
)
1636 // Do some sanity checking on the flags used: not all values can be used
1638 wxASSERT_MSG( !(flags
& wxSOCKET_NOWAIT
) ||
1639 !(flags
& (wxSOCKET_WAITALL
| wxSOCKET_BLOCK
)),
1640 "Using wxSOCKET_WAITALL or wxSOCKET_BLOCK with "
1641 "wxSOCKET_NOWAIT doesn't make sense" );
1647 // --------------------------------------------------------------------------
1649 // --------------------------------------------------------------------------
1651 void wxSocketBase::OnRequest(wxSocketNotify notification
)
1653 wxSocketEventFlags flag
= 0;
1654 switch ( notification
)
1656 case wxSOCKET_INPUT
:
1657 flag
= wxSOCKET_INPUT_FLAG
;
1660 case wxSOCKET_OUTPUT
:
1661 flag
= wxSOCKET_OUTPUT_FLAG
;
1664 case wxSOCKET_CONNECTION
:
1665 flag
= wxSOCKET_CONNECTION_FLAG
;
1667 // we're now successfully connected
1669 m_establishing
= false;
1671 // error was previously set to wxSOCKET_WOULDBLOCK, but this is not
1672 // the case any longer
1673 SetError(wxSOCKET_NOERROR
);
1677 flag
= wxSOCKET_LOST_FLAG
;
1679 // if we lost the connection the socket is now closed and not
1680 // connected any more
1681 m_connected
= false;
1686 wxFAIL_MSG( "unknown wxSocket notification" );
1689 // remember the events which were generated for this socket, we're going to
1690 // use this in DoWait()
1691 m_eventsgot
|= flag
;
1693 // send the wx event if enabled and we're interested in it
1694 if ( m_notify
&& (m_eventmask
& flag
) && m_handler
)
1696 // don't generate the events when we're inside DoWait() called from our
1697 // own code as we are going to consume the data that has just become
1698 // available ourselves and the user code won't see it at all
1699 if ( (notification
== wxSOCKET_INPUT
&& m_reading
) ||
1700 (notification
== wxSOCKET_OUTPUT
&& m_writing
) )
1705 wxSocketEvent
event(m_id
);
1706 event
.m_event
= notification
;
1707 event
.m_clientData
= m_clientData
;
1708 event
.SetEventObject(this);
1710 m_handler
->AddPendingEvent(event
);
1714 void wxSocketBase::Notify(bool notify
)
1719 void wxSocketBase::SetNotify(wxSocketEventFlags flags
)
1721 m_eventmask
= flags
;
1724 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
)
1726 m_handler
= &handler
;
1730 // --------------------------------------------------------------------------
1732 // --------------------------------------------------------------------------
1734 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
)
1738 if (m_unread
== NULL
)
1739 m_unread
= malloc(size
);
1744 tmp
= malloc(m_unrd_size
+ size
);
1745 memcpy((char *)tmp
+ size
, m_unread
, m_unrd_size
);
1751 m_unrd_size
+= size
;
1753 memcpy(m_unread
, buffer
, size
);
1756 wxUint32
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
)
1758 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1763 if (size
> (m_unrd_size
-m_unrd_cur
))
1764 size
= m_unrd_size
-m_unrd_cur
;
1766 memcpy(buffer
, (char *)m_unread
+ m_unrd_cur
, size
);
1771 if (m_unrd_size
== m_unrd_cur
)
1784 // ==========================================================================
1786 // ==========================================================================
1788 // --------------------------------------------------------------------------
1790 // --------------------------------------------------------------------------
1792 wxSocketServer::wxSocketServer(const wxSockAddress
& addr
,
1793 wxSocketFlags flags
)
1794 : wxSocketBase(flags
, wxSOCKET_SERVER
)
1796 wxLogTrace( wxTRACE_Socket
, wxT("Opening wxSocketServer") );
1798 wxSocketManager
* const manager
= wxSocketManager::Get();
1799 m_impl
= manager
? manager
->CreateSocket(*this) : NULL
;
1803 wxLogTrace( wxTRACE_Socket
, wxT("*** Failed to create m_impl") );
1807 // Setup the socket as server
1808 m_impl
->SetLocal(addr
.GetAddress());
1810 if (GetFlags() & wxSOCKET_REUSEADDR
) {
1811 m_impl
->SetReusable();
1813 if (GetFlags() & wxSOCKET_BROADCAST
) {
1814 m_impl
->SetBroadcast();
1816 if (GetFlags() & wxSOCKET_NOBIND
) {
1817 m_impl
->DontDoBind();
1820 if (m_impl
->CreateServer() != wxSOCKET_NOERROR
)
1824 wxLogTrace( wxTRACE_Socket
, wxT("*** CreateServer() failed") );
1828 // Notice that we need a cast as wxSOCKET_T is 64 bit under Win64 and that
1829 // the cast is safe because a wxSOCKET_T is a handle and so limited to 32
1830 // (or, actually, even 24) bit values anyhow.
1831 wxLogTrace( wxTRACE_Socket
, wxT("wxSocketServer on fd %u"),
1832 static_cast<unsigned>(m_impl
->m_fd
) );
1835 // --------------------------------------------------------------------------
1837 // --------------------------------------------------------------------------
1839 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
)
1841 if ( !m_impl
|| (m_impl
->m_fd
== INVALID_SOCKET
) || !m_impl
->IsServer() )
1843 wxFAIL_MSG( "can only be called for a valid server socket" );
1845 SetError(wxSOCKET_INVSOCK
);
1852 // wait until we get a connection
1853 if ( !m_impl
->SelectWithTimeout(wxSOCKET_INPUT_FLAG
) )
1855 SetError(wxSOCKET_TIMEDOUT
);
1861 sock
.m_impl
= m_impl
->Accept(sock
);
1865 SetError(m_impl
->GetLastError());
1870 sock
.m_type
= wxSOCKET_BASE
;
1871 sock
.m_connected
= true;
1876 wxSocketBase
*wxSocketServer::Accept(bool wait
)
1878 wxSocketBase
* sock
= new wxSocketBase();
1880 sock
->SetFlags(m_flags
);
1882 if (!AcceptWith(*sock
, wait
))
1891 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
)
1893 return DoWait(seconds
, milliseconds
, wxSOCKET_CONNECTION_FLAG
) == 1;
1896 wxSOCKET_T
wxSocketBase::GetSocket() const
1898 wxASSERT_MSG( m_impl
, wxS("Socket not initialised") );
1900 return m_impl
->m_fd
;
1904 bool wxSocketBase::GetOption(int level
, int optname
, void *optval
, int *optlen
)
1906 wxASSERT_MSG( m_impl
, wxT("Socket not initialised") );
1908 SOCKOPTLEN_T lenreal
= *optlen
;
1909 if ( getsockopt(m_impl
->m_fd
, level
, optname
,
1910 static_cast<char *>(optval
), &lenreal
) != 0 )
1919 wxSocketBase::SetOption(int level
, int optname
, const void *optval
, int optlen
)
1921 wxASSERT_MSG( m_impl
, wxT("Socket not initialised") );
1923 return setsockopt(m_impl
->m_fd
, level
, optname
,
1924 static_cast<const char *>(optval
), optlen
) == 0;
1927 bool wxSocketBase::SetLocal(const wxIPV4address
& local
)
1929 m_localAddress
= local
;
1934 // ==========================================================================
1936 // ==========================================================================
1938 // --------------------------------------------------------------------------
1940 // --------------------------------------------------------------------------
1942 wxSocketClient::wxSocketClient(wxSocketFlags flags
)
1943 : wxSocketBase(flags
, wxSOCKET_CLIENT
)
1945 m_initialRecvBufferSize
=
1946 m_initialSendBufferSize
= -1;
1949 // --------------------------------------------------------------------------
1951 // --------------------------------------------------------------------------
1953 bool wxSocketClient::DoConnect(const wxSockAddress
& remote
,
1954 const wxSockAddress
* local
,
1959 // Shutdown and destroy the old socket
1964 m_connected
= false;
1965 m_establishing
= false;
1967 // Create and set up the new one
1968 wxSocketManager
* const manager
= wxSocketManager::Get();
1969 m_impl
= manager
? manager
->CreateSocket(*this) : NULL
;
1973 // Reuse makes sense for clients too, if we are trying to rebind to the same port
1974 if (GetFlags() & wxSOCKET_REUSEADDR
)
1975 m_impl
->SetReusable();
1976 if (GetFlags() & wxSOCKET_BROADCAST
)
1977 m_impl
->SetBroadcast();
1978 if (GetFlags() & wxSOCKET_NOBIND
)
1979 m_impl
->DontDoBind();
1981 // Bind to the local IP address and port, when provided or if one had been
1983 if ( !local
&& m_localAddress
.GetAddress().IsOk() )
1984 local
= &m_localAddress
;
1987 m_impl
->SetLocal(local
->GetAddress());
1989 m_impl
->SetInitialSocketBuffers(m_initialRecvBufferSize
, m_initialSendBufferSize
);
1991 m_impl
->SetPeer(remote
.GetAddress());
1993 // Finally do create the socket and connect to the peer
1994 const wxSocketError err
= m_impl
->CreateClient(wait
);
1996 if ( err
!= wxSOCKET_NOERROR
)
1998 if ( err
== wxSOCKET_WOULDBLOCK
)
2000 wxASSERT_MSG( !wait
, "shouldn't get this for blocking connect" );
2002 m_establishing
= true;
2012 bool wxSocketClient::Connect(const wxSockAddress
& remote
, bool wait
)
2014 return DoConnect(remote
, NULL
, wait
);
2017 bool wxSocketClient::Connect(const wxSockAddress
& remote
,
2018 const wxSockAddress
& local
,
2021 return DoConnect(remote
, &local
, wait
);
2024 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
)
2028 // this happens if the initial attempt to connect succeeded without
2033 wxCHECK_MSG( m_establishing
&& m_impl
, false,
2034 "No connection establishment attempt in progress" );
2036 // notice that we return true even if DoWait() returned -1, i.e. if an
2037 // error occurred and connection was lost: this is intentional as we should
2038 // return false only if timeout expired without anything happening
2039 return DoWait(seconds
, milliseconds
, wxSOCKET_CONNECTION_FLAG
) != 0;
2042 // ==========================================================================
2044 // ==========================================================================
2046 wxDatagramSocket::wxDatagramSocket( const wxSockAddress
& addr
,
2047 wxSocketFlags flags
)
2048 : wxSocketBase( flags
, wxSOCKET_DATAGRAM
)
2050 // Create the socket
2051 wxSocketManager
* const manager
= wxSocketManager::Get();
2052 m_impl
= manager
? manager
->CreateSocket(*this) : NULL
;
2057 // Setup the socket as non connection oriented
2058 m_impl
->SetLocal(addr
.GetAddress());
2059 if (flags
& wxSOCKET_REUSEADDR
)
2061 m_impl
->SetReusable();
2063 if (GetFlags() & wxSOCKET_BROADCAST
)
2065 m_impl
->SetBroadcast();
2067 if (GetFlags() & wxSOCKET_NOBIND
)
2069 m_impl
->DontDoBind();
2072 if ( m_impl
->CreateUDP() != wxSOCKET_NOERROR
)
2078 // Initialize all stuff
2079 m_connected
= false;
2080 m_establishing
= false;
2083 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
,
2092 wxDatagramSocket
& wxDatagramSocket::SendTo( const wxSockAddress
& addr
,
2096 wxASSERT_MSG( m_impl
, wxT("Socket not initialised") );
2098 m_impl
->SetPeer(addr
.GetAddress());
2103 // ==========================================================================
2105 // ==========================================================================
2107 class wxSocketModule
: public wxModule
2110 virtual bool OnInit()
2112 // wxSocketBase will call Initialize() itself only if sockets are
2113 // really used, don't do it from here
2117 virtual void OnExit()
2119 if ( wxSocketBase::IsInitialized() )
2120 wxSocketBase::Shutdown();
2124 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
2127 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)
2129 #if defined(wxUSE_SELECT_DISPATCHER) && wxUSE_SELECT_DISPATCHER
2130 // NOTE: we need to force linking against socketiohandler.cpp otherwise in
2131 // static builds of wxWidgets the ManagerSetter::ManagerSetter ctor
2132 // contained there wouldn't be ever called
2133 wxFORCE_LINK_MODULE( socketiohandler
)
2136 // same for ManagerSetter in the MSW file
2138 wxFORCE_LINK_MODULE( mswsocket
)
2141 // and for OSXManagerSetter in the OS X one
2143 wxFORCE_LINK_MODULE( osxsocket
)
2146 #endif // wxUSE_SOCKETS