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 // We can be passed only wxSOCKET_WAITALL{_READ,_WRITE} or
176 // wxSOCKET_NOWAIT{_READ,_WRITE} normally.
177 wxASSERT_MSG( !(flag
& wxSOCKET_WAITALL
) || !(flag
& wxSOCKET_NOWAIT
),
180 // preserve wxSOCKET_BLOCK value when switching to wxSOCKET_WAITALL
181 // mode but not when switching to wxSOCKET_NOWAIT as the latter is
182 // incompatible with wxSOCKET_BLOCK
183 if ( flag
!= wxSOCKET_NOWAIT
)
184 flag
|= m_oldflags
& wxSOCKET_BLOCK
;
186 socket
->SetFlags(flag
);
189 ~wxSocketWaitModeChanger()
191 m_socket
->SetFlags(m_oldflags
);
195 wxSocketBase
* const m_socket
;
196 const int m_oldflags
;
198 wxDECLARE_NO_COPY_CLASS(wxSocketWaitModeChanger
);
201 // wxSocketRead/WriteGuard are instantiated before starting reading
202 // from/writing to the socket
203 class wxSocketReadGuard
206 wxSocketReadGuard(wxSocketBase
*socket
)
209 wxASSERT_MSG( !m_socket
->m_reading
, "read reentrancy?" );
211 m_socket
->m_reading
= true;
216 m_socket
->m_reading
= false;
218 // connection could have been lost while reading, in this case calling
219 // ReenableEvents() would assert and is not necessary anyhow
220 wxSocketImpl
* const impl
= m_socket
->m_impl
;
221 if ( impl
&& impl
->m_fd
!= INVALID_SOCKET
)
222 impl
->ReenableEvents(wxSOCKET_INPUT_FLAG
);
226 wxSocketBase
* const m_socket
;
228 wxDECLARE_NO_COPY_CLASS(wxSocketReadGuard
);
231 class wxSocketWriteGuard
234 wxSocketWriteGuard(wxSocketBase
*socket
)
237 wxASSERT_MSG( !m_socket
->m_writing
, "write reentrancy?" );
239 m_socket
->m_writing
= true;
242 ~wxSocketWriteGuard()
244 m_socket
->m_writing
= false;
246 wxSocketImpl
* const impl
= m_socket
->m_impl
;
247 if ( impl
&& impl
->m_fd
!= INVALID_SOCKET
)
248 impl
->ReenableEvents(wxSOCKET_OUTPUT_FLAG
);
252 wxSocketBase
* const m_socket
;
254 wxDECLARE_NO_COPY_CLASS(wxSocketWriteGuard
);
257 // ============================================================================
259 // ============================================================================
261 wxSocketManager
*wxSocketManager::ms_manager
= NULL
;
264 void wxSocketManager::Set(wxSocketManager
*manager
)
266 wxASSERT_MSG( !ms_manager
, "too late to set manager now" );
268 ms_manager
= manager
;
272 void wxSocketManager::Init()
274 wxASSERT_MSG( !ms_manager
, "shouldn't be initialized twice" );
277 Details: Initialize() creates a hidden window as a sink for socket
278 events, such as 'read completed'. wxMSW has only one message loop
279 for the main thread. If Initialize is called in a secondary thread,
280 the socket window will be created for the secondary thread, but
281 since there is no message loop on this thread, it will never
282 receive events and all socket operations will time out.
283 BTW, the main thread must not be stopped using sleep or block
284 on a semaphore (a bad idea in any case) or socket operations
287 On the Mac side, Initialize() stores a pointer to the CFRunLoop for
288 the main thread. Because secondary threads do not have run loops,
289 adding event notifications to the "Current" loop would have no
290 effect at all, events would never fire.
292 wxASSERT_MSG( wxIsMainThread(),
293 "sockets must be initialized from the main thread" );
295 wxAppConsole
* const app
= wxAppConsole::GetInstance();
296 wxCHECK_RET( app
, "sockets can't be initialized without wxApp" );
298 ms_manager
= app
->GetTraits()->GetSocketManager();
301 // ==========================================================================
303 // ==========================================================================
305 wxSocketImpl::wxSocketImpl(wxSocketBase
& wxsocket
)
306 : m_wxsocket(&wxsocket
)
308 m_fd
= INVALID_SOCKET
;
309 m_error
= wxSOCKET_NOERROR
;
313 SetTimeout(wxsocket
.GetTimeout() * 1000);
315 m_establishing
= false;
319 m_initialRecvBufferSize
= -1;
320 m_initialSendBufferSize
= -1;
323 wxSocketImpl::~wxSocketImpl()
325 if ( m_fd
!= INVALID_SOCKET
)
329 bool wxSocketImpl::PreCreateCheck(const wxSockAddressImpl
& addr
)
331 if ( m_fd
!= INVALID_SOCKET
)
333 m_error
= wxSOCKET_INVSOCK
;
339 m_error
= wxSOCKET_INVADDR
;
346 void wxSocketImpl::PostCreation()
348 // FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option
350 EnableSocketOption(SO_NOSIGPIPE
);
354 EnableSocketOption(SO_REUSEADDR
);
358 wxASSERT_MSG( !m_stream
, "broadcasting is for datagram sockets only" );
360 EnableSocketOption(SO_BROADCAST
);
363 if ( m_initialRecvBufferSize
>= 0 )
364 SetSocketOption(SO_RCVBUF
, m_initialRecvBufferSize
);
365 if ( m_initialSendBufferSize
>= 0 )
366 SetSocketOption(SO_SNDBUF
, m_initialSendBufferSize
);
368 // we always put our sockets in unblocked mode and handle blocking
369 // ourselves in DoRead/Write() if wxSOCKET_WAITALL is specified
370 UnblockAndRegisterWithEventLoop();
373 wxSocketError
wxSocketImpl::UpdateLocalAddress()
375 if ( !m_local
.IsOk() )
377 // ensure that we have a valid object using the correct family: correct
378 // being the same one as our peer uses as we have no other way to
380 m_local
.Create(m_peer
.GetFamily());
383 WX_SOCKLEN_T lenAddr
= m_local
.GetLen();
384 if ( getsockname(m_fd
, m_local
.GetWritableAddr(), &lenAddr
) != 0 )
387 m_error
= wxSOCKET_IOERR
;
391 return wxSOCKET_NOERROR
;
394 wxSocketError
wxSocketImpl::CreateServer()
396 if ( !PreCreateCheck(m_local
) )
402 // do create the socket
403 m_fd
= socket(m_local
.GetFamily(), SOCK_STREAM
, 0);
405 if ( m_fd
== INVALID_SOCKET
)
407 m_error
= wxSOCKET_IOERR
;
408 return wxSOCKET_IOERR
;
413 // and then bind to and listen on it
415 // FIXME: should we test for m_dobind here?
416 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
417 m_error
= wxSOCKET_IOERR
;
421 if ( listen(m_fd
, 5) != 0 )
422 m_error
= wxSOCKET_IOERR
;
431 // finally retrieve the address we effectively bound to
432 return UpdateLocalAddress();
435 wxSocketError
wxSocketImpl::CreateClient(bool wait
)
437 if ( !PreCreateCheck(m_peer
) )
440 m_fd
= socket(m_peer
.GetFamily(), SOCK_STREAM
, 0);
442 if ( m_fd
== INVALID_SOCKET
)
444 m_error
= wxSOCKET_IOERR
;
445 return wxSOCKET_IOERR
;
450 // If a local address has been set, then bind to it before calling connect
451 if ( m_local
.IsOk() )
453 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
456 m_error
= wxSOCKET_IOERR
;
462 int rc
= connect(m_fd
, m_peer
.GetAddr(), m_peer
.GetLen());
463 if ( rc
== SOCKET_ERROR
)
465 wxSocketError err
= GetLastError();
466 if ( err
== wxSOCKET_WOULDBLOCK
)
468 m_establishing
= true;
470 // block waiting for connection if we should (otherwise just return
471 // wxSOCKET_WOULDBLOCK to the caller)
474 err
= SelectWithTimeout(wxSOCKET_CONNECTION_FLAG
)
477 m_establishing
= false;
485 m_error
= wxSOCKET_NOERROR
;
492 wxSocketError
wxSocketImpl::CreateUDP()
494 if ( !PreCreateCheck(m_local
) )
500 m_fd
= socket(m_local
.GetFamily(), SOCK_DGRAM
, 0);
502 if ( m_fd
== INVALID_SOCKET
)
504 m_error
= wxSOCKET_IOERR
;
505 return wxSOCKET_IOERR
;
512 if ( bind(m_fd
, m_local
.GetAddr(), m_local
.GetLen()) != 0 )
515 m_error
= wxSOCKET_IOERR
;
519 return UpdateLocalAddress();
522 return wxSOCKET_NOERROR
;
525 wxSocketImpl
*wxSocketImpl::Accept(wxSocketBase
& wxsocket
)
527 wxSockAddressStorage from
;
528 WX_SOCKLEN_T fromlen
= sizeof(from
);
529 const wxSOCKET_T fd
= accept(m_fd
, &from
.addr
, &fromlen
);
531 // accepting is similar to reading in the sense that it resets "ready for
532 // read" flag on the socket
533 ReenableEvents(wxSOCKET_INPUT_FLAG
);
535 if ( fd
== INVALID_SOCKET
)
538 wxSocketManager
* const manager
= wxSocketManager::Get();
542 wxSocketImpl
* const sock
= manager
->CreateSocket(wxsocket
);
547 sock
->m_peer
= wxSockAddressImpl(from
.addr
, fromlen
);
549 sock
->UnblockAndRegisterWithEventLoop();
555 void wxSocketImpl::Close()
557 if ( m_fd
!= INVALID_SOCKET
)
560 m_fd
= INVALID_SOCKET
;
564 void wxSocketImpl::Shutdown()
566 if ( m_fd
!= INVALID_SOCKET
)
568 shutdown(m_fd
, 1 /* SD_SEND */);
574 * Sets the timeout for blocking calls. Time is expressed in
577 void wxSocketImpl::SetTimeout(unsigned long millis
)
579 SetTimeValFromMS(m_timeout
, millis
);
582 void wxSocketImpl::NotifyOnStateChange(wxSocketNotify event
)
584 m_wxsocket
->OnRequest(event
);
587 /* Address handling */
588 wxSocketError
wxSocketImpl::SetLocal(const wxSockAddressImpl
& local
)
590 /* the socket must be initialized, or it must be a server */
591 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
593 m_error
= wxSOCKET_INVSOCK
;
594 return wxSOCKET_INVSOCK
;
599 m_error
= wxSOCKET_INVADDR
;
600 return wxSOCKET_INVADDR
;
605 return wxSOCKET_NOERROR
;
608 wxSocketError
wxSocketImpl::SetPeer(const wxSockAddressImpl
& peer
)
612 m_error
= wxSOCKET_INVADDR
;
613 return wxSOCKET_INVADDR
;
618 return wxSOCKET_NOERROR
;
621 const wxSockAddressImpl
& wxSocketImpl::GetLocal()
623 if ( !m_local
.IsOk() )
624 UpdateLocalAddress();
629 // ----------------------------------------------------------------------------
631 // ----------------------------------------------------------------------------
633 // this macro wraps the given expression (normally a syscall) in a loop which
634 // ignores any interruptions, i.e. reevaluates it again if it failed and errno
637 #define DO_WHILE_EINTR( rc, syscall ) \
641 while ( rc == -1 && errno == EINTR )
643 #define DO_WHILE_EINTR( rc, syscall ) rc = (syscall)
646 int wxSocketImpl::RecvStream(void *buffer
, int size
)
649 DO_WHILE_EINTR( ret
, recv(m_fd
, static_cast<char *>(buffer
), size
, 0) );
653 // receiving 0 bytes for a TCP socket indicates that the connection was
654 // closed by peer so shut down our end as well (for UDP sockets empty
655 // datagrams are also possible)
656 m_establishing
= false;
657 NotifyOnStateChange(wxSOCKET_LOST
);
661 // do not return an error in this case however
667 int wxSocketImpl::SendStream(const void *buffer
, int size
)
669 #ifdef wxNEEDS_IGNORE_SIGPIPE
670 IgnoreSignal
ignore(SIGPIPE
);
674 DO_WHILE_EINTR( ret
, send(m_fd
, static_cast<const char *>(buffer
), size
,
675 wxSOCKET_MSG_NOSIGNAL
) );
680 int wxSocketImpl::RecvDgram(void *buffer
, int size
)
682 wxSockAddressStorage from
;
683 WX_SOCKLEN_T fromlen
= sizeof(from
);
686 DO_WHILE_EINTR( ret
, recvfrom(m_fd
, static_cast<char *>(buffer
), size
,
687 0, &from
.addr
, &fromlen
) );
689 if ( ret
== SOCKET_ERROR
)
692 m_peer
= wxSockAddressImpl(from
.addr
, fromlen
);
693 if ( !m_peer
.IsOk() )
699 int wxSocketImpl::SendDgram(const void *buffer
, int size
)
701 if ( !m_peer
.IsOk() )
703 m_error
= wxSOCKET_INVADDR
;
708 DO_WHILE_EINTR( ret
, sendto(m_fd
, static_cast<const char *>(buffer
), size
,
709 0, m_peer
.GetAddr(), m_peer
.GetLen()) );
714 int wxSocketImpl::Read(void *buffer
, int size
)
716 // server sockets can't be used for IO, only to accept new connections
717 if ( m_fd
== INVALID_SOCKET
|| m_server
)
719 m_error
= wxSOCKET_INVSOCK
;
723 int ret
= m_stream
? RecvStream(buffer
, size
)
724 : RecvDgram(buffer
, size
);
726 m_error
= ret
== SOCKET_ERROR
? GetLastError() : wxSOCKET_NOERROR
;
731 int wxSocketImpl::Write(const void *buffer
, int size
)
733 if ( m_fd
== INVALID_SOCKET
|| m_server
)
735 m_error
= wxSOCKET_INVSOCK
;
739 int ret
= m_stream
? SendStream(buffer
, size
)
740 : SendDgram(buffer
, size
);
742 m_error
= ret
== SOCKET_ERROR
? GetLastError() : wxSOCKET_NOERROR
;
747 // ==========================================================================
749 // ==========================================================================
751 // --------------------------------------------------------------------------
752 // Initialization and shutdown
753 // --------------------------------------------------------------------------
758 // counts the number of calls to Initialize() minus the number of calls to
759 // Shutdown(): we don't really need it any more but it was documented that
760 // Shutdown() must be called the same number of times as Initialize() and using
761 // a counter helps us to check it
762 int gs_socketInitCount
= 0;
764 } // anonymous namespace
766 bool wxSocketBase::IsInitialized()
768 wxASSERT_MSG( wxIsMainThread(), "unsafe to call from other threads" );
770 return gs_socketInitCount
!= 0;
773 bool wxSocketBase::Initialize()
775 wxCHECK_MSG( wxIsMainThread(), false,
776 "must be called from the main thread" );
778 if ( !gs_socketInitCount
)
780 wxSocketManager
* const manager
= wxSocketManager::Get();
781 if ( !manager
|| !manager
->OnInit() )
785 gs_socketInitCount
++;
790 void wxSocketBase::Shutdown()
792 wxCHECK_RET( wxIsMainThread(), "must be called from the main thread" );
794 wxCHECK_RET( gs_socketInitCount
> 0, "too many calls to Shutdown()" );
796 if ( !--gs_socketInitCount
)
798 wxSocketManager
* const manager
= wxSocketManager::Get();
799 wxCHECK_RET( manager
, "should have a socket manager" );
805 // --------------------------------------------------------------------------
807 // --------------------------------------------------------------------------
809 void wxSocketBase::Init()
812 m_type
= wxSOCKET_UNINIT
;
825 m_beingDeleted
= false;
840 // when we create the first socket in the main thread we initialize the
841 // OS-dependent socket stuff: notice that this means that the user code
842 // needs to call wxSocket::Initialize() itself if the first socket it
843 // creates is not created in the main thread
844 if ( wxIsMainThread() )
848 wxLogError(_("Cannot initialize sockets"));
853 wxSocketBase::wxSocketBase()
858 wxSocketBase::wxSocketBase(wxSocketFlags flags
, wxSocketType type
)
867 wxSocketBase::~wxSocketBase()
869 // Shutdown and close the socket
873 // Destroy the implementation object
876 // Free the pushback buffer
880 bool wxSocketBase::Destroy()
882 // Delayed destruction: the socket will be deleted during the next idle
883 // loop iteration. This ensures that all pending events have been
885 m_beingDeleted
= true;
887 // Shutdown and close the socket
890 // Suppress events from now on
893 // Schedule this object for deletion instead of destroying it right now if
894 // it can have other events pending for it and we have a way to do it.
896 // Notice that sockets used in other threads won't have any events for them
897 // and we shouldn't use delayed destruction mechanism for them as it's not
899 if ( wxIsMainThread() && wxTheApp
)
901 wxTheApp
->ScheduleForDestruction(this);
905 // in wxBase we might have no app object at all, don't leak memory
912 // ----------------------------------------------------------------------------
914 // ----------------------------------------------------------------------------
916 void wxSocketBase::SetError(wxSocketError error
)
918 m_impl
->m_error
= error
;
921 wxSocketError
wxSocketBase::LastError() const
923 return m_impl
->GetError();
926 // --------------------------------------------------------------------------
928 // --------------------------------------------------------------------------
930 // The following IO operations update m_lcount:
931 // {Read, Write, ReadMsg, WriteMsg, Peek, Unread, Discard}
932 bool wxSocketBase::Close()
934 // Interrupt pending waits
940 m_establishing
= false;
944 void wxSocketBase::ShutdownOutput()
950 wxSocketBase
& wxSocketBase::Read(void* buffer
, wxUint32 nbytes
)
952 wxSocketReadGuard
read(this);
954 m_lcount_read
= DoRead(buffer
, nbytes
);
955 m_lcount
= m_lcount_read
;
960 wxUint32
wxSocketBase::DoRead(void* buffer_
, wxUint32 nbytes
)
962 wxCHECK_MSG( m_impl
, 0, "socket must be valid" );
964 // We use pointer arithmetic here which doesn't work with void pointers.
965 char *buffer
= static_cast<char *>(buffer_
);
966 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
968 // Try the push back buffer first, even before checking whether the socket
969 // is valid to allow reading previously pushed back data from an already
971 wxUint32 total
= GetPushback(buffer
, nbytes
, false);
977 // our socket is non-blocking so Read() will return immediately if
978 // there is nothing to read yet and it's more efficient to try it first
979 // before entering DoWait() which is going to start dispatching GUI
980 // events and, even more importantly, we must do this under Windows
981 // where we're not going to get notifications about socket being ready
982 // for reading before we read all the existing data from it
983 const int ret
= !m_impl
->m_stream
|| m_connected
984 ? m_impl
->Read(buffer
, nbytes
)
988 if ( m_impl
->GetLastError() == wxSOCKET_WOULDBLOCK
)
990 // if we don't want to wait, just return immediately
991 if ( m_flags
& wxSOCKET_NOWAIT_READ
)
993 // this shouldn't be counted as an error in this case
994 SetError(wxSOCKET_NOERROR
);
998 // otherwise wait until the socket becomes ready for reading or
999 // an error occurs on it
1000 if ( !DoWaitWithTimeout(wxSOCKET_INPUT_FLAG
) )
1002 // and exit if the timeout elapsed before it did
1003 SetError(wxSOCKET_TIMEDOUT
);
1010 else // "real" error
1012 SetError(wxSOCKET_IOERR
);
1016 else if ( ret
== 0 )
1018 // for connection-oriented (e.g. TCP) sockets we can only read
1019 // 0 bytes if the other end has been closed, and for connectionless
1020 // ones (UDP) this flag doesn't make sense anyhow so we can set it
1021 // to true too without doing any harm
1024 // we're not going to read anything else and so if we haven't read
1025 // anything (or not everything in wxSOCKET_WAITALL case) already,
1027 if ( (m_flags
& wxSOCKET_WAITALL_READ
) || !total
)
1028 SetError(wxSOCKET_IOERR
);
1034 // if we are happy to read something and not the entire nbytes bytes,
1036 if ( !(m_flags
& wxSOCKET_WAITALL_READ
) )
1046 wxSocketBase
& wxSocketBase::ReadMsg(void* buffer
, wxUint32 nbytes
)
1050 unsigned char sig
[4];
1051 unsigned char len
[4];
1054 wxSocketReadGuard
read(this);
1056 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_WAITALL_READ
);
1059 if ( DoRead(&msg
, sizeof(msg
)) == sizeof(msg
) )
1061 wxUint32 sig
= (wxUint32
)msg
.sig
[0];
1062 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
1063 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
1064 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
1066 if ( sig
== 0xfeeddead )
1068 wxUint32 len
= (wxUint32
)msg
.len
[0];
1069 len
|= (wxUint32
)(msg
.len
[1] << 8);
1070 len
|= (wxUint32
)(msg
.len
[2] << 16);
1071 len
|= (wxUint32
)(msg
.len
[3] << 24);
1076 len2
= len
- nbytes
;
1082 // Don't attempt to read if the msg was zero bytes long.
1083 m_lcount_read
= len
? DoRead(buffer
, len
) : 0;
1084 m_lcount
= m_lcount_read
;
1088 char discard_buffer
[MAX_DISCARD_SIZE
];
1091 // NOTE: discarded bytes don't add to m_lcount.
1094 discard_len
= len2
> MAX_DISCARD_SIZE
1097 discard_len
= DoRead(discard_buffer
, (wxUint32
)discard_len
);
1098 len2
-= (wxUint32
)discard_len
;
1100 while ((discard_len
> 0) && len2
);
1103 if ( !len2
&& DoRead(&msg
, sizeof(msg
)) == sizeof(msg
) )
1105 sig
= (wxUint32
)msg
.sig
[0];
1106 sig
|= (wxUint32
)(msg
.sig
[1] << 8);
1107 sig
|= (wxUint32
)(msg
.sig
[2] << 16);
1108 sig
|= (wxUint32
)(msg
.sig
[3] << 24);
1110 if ( sig
== 0xdeadfeed )
1117 SetError(wxSOCKET_IOERR
);
1122 wxSocketBase
& wxSocketBase::Peek(void* buffer
, wxUint32 nbytes
)
1124 wxSocketReadGuard
read(this);
1126 // Peek() should never block
1127 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_NOWAIT
);
1129 m_lcount
= DoRead(buffer
, nbytes
);
1131 Pushback(buffer
, m_lcount
);
1136 wxSocketBase
& wxSocketBase::Write(const void *buffer
, wxUint32 nbytes
)
1138 wxSocketWriteGuard
write(this);
1140 m_lcount_write
= DoWrite(buffer
, nbytes
);
1141 m_lcount
= m_lcount_write
;
1146 // This function is a mirror image of DoRead() except that it doesn't use the
1147 // push back buffer and doesn't treat 0 return value specially (normally this
1148 // shouldn't happen at all here), so please see comments there for explanations
1149 wxUint32
wxSocketBase::DoWrite(const void *buffer_
, wxUint32 nbytes
)
1151 wxCHECK_MSG( m_impl
, 0, "socket must be valid" );
1153 const char *buffer
= static_cast<const char *>(buffer_
);
1154 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1159 if ( m_impl
->m_stream
&& !m_connected
)
1161 if ( (m_flags
& wxSOCKET_WAITALL_WRITE
) || !total
)
1162 SetError(wxSOCKET_IOERR
);
1166 const int ret
= m_impl
->Write(buffer
, nbytes
);
1169 if ( m_impl
->GetLastError() == wxSOCKET_WOULDBLOCK
)
1171 if ( m_flags
& wxSOCKET_NOWAIT_WRITE
)
1174 if ( !DoWaitWithTimeout(wxSOCKET_OUTPUT_FLAG
) )
1176 SetError(wxSOCKET_TIMEDOUT
);
1182 else // "real" error
1184 SetError(wxSOCKET_IOERR
);
1191 if ( !(m_flags
& wxSOCKET_WAITALL_WRITE
) )
1201 wxSocketBase
& wxSocketBase::WriteMsg(const void *buffer
, wxUint32 nbytes
)
1205 unsigned char sig
[4];
1206 unsigned char len
[4];
1209 wxSocketWriteGuard
write(this);
1211 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_WAITALL_WRITE
);
1213 msg
.sig
[0] = (unsigned char) 0xad;
1214 msg
.sig
[1] = (unsigned char) 0xde;
1215 msg
.sig
[2] = (unsigned char) 0xed;
1216 msg
.sig
[3] = (unsigned char) 0xfe;
1218 msg
.len
[0] = (unsigned char) (nbytes
& 0xff);
1219 msg
.len
[1] = (unsigned char) ((nbytes
>> 8) & 0xff);
1220 msg
.len
[2] = (unsigned char) ((nbytes
>> 16) & 0xff);
1221 msg
.len
[3] = (unsigned char) ((nbytes
>> 24) & 0xff);
1224 if ( DoWrite(&msg
, sizeof(msg
)) == sizeof(msg
) )
1226 m_lcount_write
= DoWrite(buffer
, nbytes
);
1227 m_lcount
= m_lcount_write
;
1228 if ( m_lcount_write
== nbytes
)
1230 msg
.sig
[0] = (unsigned char) 0xed;
1231 msg
.sig
[1] = (unsigned char) 0xfe;
1232 msg
.sig
[2] = (unsigned char) 0xad;
1233 msg
.sig
[3] = (unsigned char) 0xde;
1237 msg
.len
[3] = (char) 0;
1239 if ( DoWrite(&msg
, sizeof(msg
)) == sizeof(msg
))
1245 SetError(wxSOCKET_IOERR
);
1250 wxSocketBase
& wxSocketBase::Unread(const void *buffer
, wxUint32 nbytes
)
1253 Pushback(buffer
, nbytes
);
1255 SetError(wxSOCKET_NOERROR
);
1261 wxSocketBase
& wxSocketBase::Discard()
1263 char *buffer
= new char[MAX_DISCARD_SIZE
];
1267 wxSocketReadGuard
read(this);
1269 wxSocketWaitModeChanger
changeFlags(this, wxSOCKET_NOWAIT
);
1273 ret
= DoRead(buffer
, MAX_DISCARD_SIZE
);
1276 while (ret
== MAX_DISCARD_SIZE
);
1280 SetError(wxSOCKET_NOERROR
);
1285 // --------------------------------------------------------------------------
1287 // --------------------------------------------------------------------------
1290 This function will check for the events specified in the flags parameter,
1291 and it will return a mask indicating which operations can be performed.
1293 wxSocketEventFlags
wxSocketImpl::Select(wxSocketEventFlags flags
,
1294 const timeval
*timeout
)
1296 if ( m_fd
== INVALID_SOCKET
)
1297 return (wxSOCKET_LOST_FLAG
& flags
);
1303 tv
.tv_sec
= tv
.tv_usec
= 0;
1305 // prepare the FD sets, passing NULL for the one(s) we don't use
1307 readfds
, *preadfds
= NULL
,
1308 writefds
, *pwritefds
= NULL
,
1309 exceptfds
; // always want to know about errors
1311 if ( flags
& wxSOCKET_INPUT_FLAG
)
1312 preadfds
= &readfds
;
1314 if ( flags
& wxSOCKET_OUTPUT_FLAG
)
1315 pwritefds
= &writefds
;
1317 // When using non-blocking connect() the client socket becomes connected
1318 // (successfully or not) when it becomes writable but when using
1319 // non-blocking accept() the server socket becomes connected when it
1320 // becomes readable.
1321 if ( flags
& wxSOCKET_CONNECTION_FLAG
)
1324 preadfds
= &readfds
;
1326 pwritefds
= &writefds
;
1331 wxFD_ZERO(preadfds
);
1332 wxFD_SET(m_fd
, preadfds
);
1337 wxFD_ZERO(pwritefds
);
1338 wxFD_SET(m_fd
, pwritefds
);
1341 wxFD_ZERO(&exceptfds
);
1342 wxFD_SET(m_fd
, &exceptfds
);
1344 const int rc
= select(m_fd
+ 1, preadfds
, pwritefds
, &exceptfds
, &tv
);
1346 // check for errors first
1347 if ( rc
== -1 || wxFD_ISSET(m_fd
, &exceptfds
) )
1349 m_establishing
= false;
1351 return wxSOCKET_LOST_FLAG
& flags
;
1357 wxASSERT_MSG( rc
== 1, "unexpected select() return value" );
1359 wxSocketEventFlags detected
= 0;
1360 if ( preadfds
&& wxFD_ISSET(m_fd
, preadfds
) )
1361 detected
|= wxSOCKET_INPUT_FLAG
;
1363 if ( pwritefds
&& wxFD_ISSET(m_fd
, pwritefds
) )
1365 // check for the case of non-blocking connect()
1366 if ( m_establishing
&& !m_server
)
1369 SOCKOPTLEN_T len
= sizeof(error
);
1370 m_establishing
= false;
1371 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1374 detected
= wxSOCKET_LOST_FLAG
;
1376 detected
|= wxSOCKET_CONNECTION_FLAG
;
1378 else // not called to get non-blocking connect() status
1380 detected
|= wxSOCKET_OUTPUT_FLAG
;
1384 return detected
& flags
;
1388 wxSocketBase::DoWait(long seconds
, long milliseconds
, wxSocketEventFlags flags
)
1390 // Use either the provided timeout or the default timeout value associated
1391 // with this socket.
1393 // TODO: allow waiting forever, see #9443
1394 const long timeout
= seconds
== -1 ? m_timeout
* 1000
1395 : seconds
* 1000 + milliseconds
;
1397 return DoWait(timeout
, flags
);
1401 wxSocketBase::DoWait(long timeout
, wxSocketEventFlags flags
)
1403 wxCHECK_MSG( m_impl
, -1, "can't wait on invalid socket" );
1405 // we're never going to become ready in a TCP client if we're not connected
1406 // any more (OTOH a server can call this to precisely wait for a connection
1407 // so do wait for it in this case and UDP client is never "connected")
1408 if ( !m_impl
->IsServer() &&
1409 m_impl
->m_stream
&& !m_connected
&& !m_establishing
)
1412 // This can be set to true from Interrupt() to exit this function a.s.a.p.
1413 m_interrupt
= false;
1416 const wxMilliClock_t timeEnd
= wxGetLocalTimeMillis() + timeout
;
1418 // Get the active event loop which we'll use for the message dispatching
1419 // when running in the main thread unless this was explicitly disabled by
1420 // setting wxSOCKET_BLOCK flag
1421 wxEventLoopBase
*eventLoop
;
1422 if ( !(m_flags
& wxSOCKET_BLOCK
) && wxIsMainThread() )
1424 eventLoop
= wxEventLoop::GetActive();
1426 else // in worker thread
1428 // We never dispatch messages from threads other than the main one.
1432 // Make sure the events we're interested in are enabled before waiting for
1433 // them: this is really necessary here as otherwise this could happen:
1434 // 1. DoRead(wxSOCKET_WAITALL) is called
1435 // 2. There is nothing to read so DoWait(wxSOCKET_INPUT_FLAG) is called
1436 // 3. Some, but not all data appears, wxSocketImplUnix::OnReadWaiting()
1437 // is called and wxSOCKET_INPUT_FLAG events are disabled in it
1438 // 4. Because of wxSOCKET_WAITALL we call DoWait() again but the events
1439 // are still disabled and we block forever
1441 // More elegant solution would be nice but for now simply re-enabling the
1442 // events here will do
1443 m_impl
->ReenableEvents(flags
& (wxSOCKET_INPUT_FLAG
| wxSOCKET_OUTPUT_FLAG
));
1446 // Wait until we receive the event we're waiting for or the timeout expires
1447 // (but note that we always execute the loop at least once, even if timeout
1448 // is 0 as this is used for polling)
1450 for ( bool firstTime
= true; !m_interrupt
; firstTime
= false )
1452 long timeLeft
= wxMilliClockToLong(timeEnd
- wxGetLocalTimeMillis());
1461 wxSocketEventFlags events
;
1464 // reset them before starting to wait
1467 eventLoop
->DispatchTimeout(timeLeft
);
1469 events
= m_eventsgot
;
1471 else // no event loop or waiting in another thread
1473 // as explained below, we should always check for wxSOCKET_LOST_FLAG
1475 SetTimeValFromMS(tv
, timeLeft
);
1476 events
= m_impl
->Select(flags
| wxSOCKET_LOST_FLAG
, &tv
);
1479 // always check for wxSOCKET_LOST_FLAG, even if flags doesn't include
1480 // it, as continuing to wait for anything else after getting it is
1482 if ( events
& wxSOCKET_LOST_FLAG
)
1484 m_connected
= false;
1485 m_establishing
= false;
1490 // otherwise mask out the bits we're not interested in
1493 // Incoming connection (server) or connection established (client)?
1494 if ( events
& wxSOCKET_CONNECTION_FLAG
)
1497 m_establishing
= false;
1502 // Data available or output buffer ready?
1503 if ( (events
& wxSOCKET_INPUT_FLAG
) || (events
& wxSOCKET_OUTPUT_FLAG
) )
1513 bool wxSocketBase::Wait(long seconds
, long milliseconds
)
1515 return DoWait(seconds
, milliseconds
,
1516 wxSOCKET_INPUT_FLAG
|
1517 wxSOCKET_OUTPUT_FLAG
|
1518 wxSOCKET_CONNECTION_FLAG
) != 0;
1521 bool wxSocketBase::WaitForRead(long seconds
, long milliseconds
)
1523 // Check pushback buffer before entering DoWait
1527 // Check if the socket is not already ready for input, if it is, there is
1528 // no need to start waiting for it (worse, we'll actually never get a
1529 // notification about the socket becoming ready if it is already under
1531 if ( m_impl
->Select(wxSOCKET_INPUT_FLAG
) )
1534 return DoWait(seconds
, milliseconds
, wxSOCKET_INPUT_FLAG
) != 0;
1538 bool wxSocketBase::WaitForWrite(long seconds
, long milliseconds
)
1540 if ( m_impl
->Select(wxSOCKET_OUTPUT_FLAG
) )
1543 return DoWait(seconds
, milliseconds
, wxSOCKET_OUTPUT_FLAG
) != 0;
1546 bool wxSocketBase::WaitForLost(long seconds
, long milliseconds
)
1548 return DoWait(seconds
, milliseconds
, wxSOCKET_LOST_FLAG
) == -1;
1551 // --------------------------------------------------------------------------
1553 // --------------------------------------------------------------------------
1556 // Get local or peer address
1559 bool wxSocketBase::GetPeer(wxSockAddress
& addr
) const
1561 wxCHECK_MSG( m_impl
, false, "invalid socket" );
1563 const wxSockAddressImpl
& peer
= m_impl
->GetPeer();
1567 addr
.SetAddress(peer
);
1572 bool wxSocketBase::GetLocal(wxSockAddress
& addr
) const
1574 wxCHECK_MSG( m_impl
, false, "invalid socket" );
1576 const wxSockAddressImpl
& local
= m_impl
->GetLocal();
1577 if ( !local
.IsOk() )
1580 addr
.SetAddress(local
);
1586 // Save and restore socket state
1589 void wxSocketBase::SaveState()
1591 wxSocketState
*state
;
1593 state
= new wxSocketState();
1595 state
->m_flags
= m_flags
;
1596 state
->m_notify
= m_notify
;
1597 state
->m_eventmask
= m_eventmask
;
1598 state
->m_clientData
= m_clientData
;
1600 m_states
.Append(state
);
1603 void wxSocketBase::RestoreState()
1605 wxList::compatibility_iterator node
;
1606 wxSocketState
*state
;
1608 node
= m_states
.GetLast();
1612 state
= (wxSocketState
*)node
->GetData();
1614 m_flags
= state
->m_flags
;
1615 m_notify
= state
->m_notify
;
1616 m_eventmask
= state
->m_eventmask
;
1617 m_clientData
= state
->m_clientData
;
1619 m_states
.Erase(node
);
1624 // Timeout and flags
1627 void wxSocketBase::SetTimeout(long seconds
)
1629 m_timeout
= seconds
;
1632 m_impl
->SetTimeout(m_timeout
* 1000);
1635 void wxSocketBase::SetFlags(wxSocketFlags flags
)
1637 // Do some sanity checking on the flags used: not all values can be used
1639 wxASSERT_MSG( !(flags
& wxSOCKET_NOWAIT
) ||
1640 !(flags
& (wxSOCKET_WAITALL
| wxSOCKET_BLOCK
)),
1641 "Using wxSOCKET_WAITALL or wxSOCKET_BLOCK with "
1642 "wxSOCKET_NOWAIT doesn't make sense" );
1648 // --------------------------------------------------------------------------
1650 // --------------------------------------------------------------------------
1652 void wxSocketBase::OnRequest(wxSocketNotify notification
)
1654 wxSocketEventFlags flag
= 0;
1655 switch ( notification
)
1657 case wxSOCKET_INPUT
:
1658 flag
= wxSOCKET_INPUT_FLAG
;
1661 case wxSOCKET_OUTPUT
:
1662 flag
= wxSOCKET_OUTPUT_FLAG
;
1665 case wxSOCKET_CONNECTION
:
1666 flag
= wxSOCKET_CONNECTION_FLAG
;
1668 // we're now successfully connected
1670 m_establishing
= false;
1672 // error was previously set to wxSOCKET_WOULDBLOCK, but this is not
1673 // the case any longer
1674 SetError(wxSOCKET_NOERROR
);
1678 flag
= wxSOCKET_LOST_FLAG
;
1680 // if we lost the connection the socket is now closed and not
1681 // connected any more
1682 m_connected
= false;
1687 wxFAIL_MSG( "unknown wxSocket notification" );
1690 // remember the events which were generated for this socket, we're going to
1691 // use this in DoWait()
1692 m_eventsgot
|= flag
;
1694 // send the wx event if enabled and we're interested in it
1695 if ( m_notify
&& (m_eventmask
& flag
) && m_handler
)
1697 // don't generate the events when we're inside DoWait() called from our
1698 // own code as we are going to consume the data that has just become
1699 // available ourselves and the user code won't see it at all
1700 if ( (notification
== wxSOCKET_INPUT
&& m_reading
) ||
1701 (notification
== wxSOCKET_OUTPUT
&& m_writing
) )
1706 wxSocketEvent
event(m_id
);
1707 event
.m_event
= notification
;
1708 event
.m_clientData
= m_clientData
;
1709 event
.SetEventObject(this);
1711 m_handler
->AddPendingEvent(event
);
1715 void wxSocketBase::Notify(bool notify
)
1720 void wxSocketBase::SetNotify(wxSocketEventFlags flags
)
1722 m_eventmask
= flags
;
1725 void wxSocketBase::SetEventHandler(wxEvtHandler
& handler
, int id
)
1727 m_handler
= &handler
;
1731 // --------------------------------------------------------------------------
1733 // --------------------------------------------------------------------------
1735 void wxSocketBase::Pushback(const void *buffer
, wxUint32 size
)
1739 if (m_unread
== NULL
)
1740 m_unread
= malloc(size
);
1745 tmp
= malloc(m_unrd_size
+ size
);
1746 memcpy((char *)tmp
+ size
, m_unread
, m_unrd_size
);
1752 m_unrd_size
+= size
;
1754 memcpy(m_unread
, buffer
, size
);
1757 wxUint32
wxSocketBase::GetPushback(void *buffer
, wxUint32 size
, bool peek
)
1759 wxCHECK_MSG( buffer
, 0, "NULL buffer" );
1764 if (size
> (m_unrd_size
-m_unrd_cur
))
1765 size
= m_unrd_size
-m_unrd_cur
;
1767 memcpy(buffer
, (char *)m_unread
+ m_unrd_cur
, size
);
1772 if (m_unrd_size
== m_unrd_cur
)
1785 // ==========================================================================
1787 // ==========================================================================
1789 // --------------------------------------------------------------------------
1791 // --------------------------------------------------------------------------
1793 wxSocketServer::wxSocketServer(const wxSockAddress
& addr
,
1794 wxSocketFlags flags
)
1795 : wxSocketBase(flags
, wxSOCKET_SERVER
)
1797 wxLogTrace( wxTRACE_Socket
, wxT("Opening wxSocketServer") );
1799 wxSocketManager
* const manager
= wxSocketManager::Get();
1800 m_impl
= manager
? manager
->CreateSocket(*this) : NULL
;
1804 wxLogTrace( wxTRACE_Socket
, wxT("*** Failed to create m_impl") );
1808 // Setup the socket as server
1809 m_impl
->SetLocal(addr
.GetAddress());
1811 if (GetFlags() & wxSOCKET_REUSEADDR
) {
1812 m_impl
->SetReusable();
1814 if (GetFlags() & wxSOCKET_BROADCAST
) {
1815 m_impl
->SetBroadcast();
1817 if (GetFlags() & wxSOCKET_NOBIND
) {
1818 m_impl
->DontDoBind();
1821 if (m_impl
->CreateServer() != wxSOCKET_NOERROR
)
1825 wxLogTrace( wxTRACE_Socket
, wxT("*** CreateServer() failed") );
1829 // Notice that we need a cast as wxSOCKET_T is 64 bit under Win64 and that
1830 // the cast is safe because a wxSOCKET_T is a handle and so limited to 32
1831 // (or, actually, even 24) bit values anyhow.
1832 wxLogTrace( wxTRACE_Socket
, wxT("wxSocketServer on fd %u"),
1833 static_cast<unsigned>(m_impl
->m_fd
) );
1836 // --------------------------------------------------------------------------
1838 // --------------------------------------------------------------------------
1840 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
, bool wait
)
1842 if ( !m_impl
|| (m_impl
->m_fd
== INVALID_SOCKET
) || !m_impl
->IsServer() )
1844 wxFAIL_MSG( "can only be called for a valid server socket" );
1846 SetError(wxSOCKET_INVSOCK
);
1853 // wait until we get a connection
1854 if ( !m_impl
->SelectWithTimeout(wxSOCKET_INPUT_FLAG
) )
1856 SetError(wxSOCKET_TIMEDOUT
);
1862 sock
.m_impl
= m_impl
->Accept(sock
);
1866 SetError(m_impl
->GetLastError());
1871 sock
.m_type
= wxSOCKET_BASE
;
1872 sock
.m_connected
= true;
1877 wxSocketBase
*wxSocketServer::Accept(bool wait
)
1879 wxSocketBase
* sock
= new wxSocketBase();
1881 sock
->SetFlags(m_flags
);
1883 if (!AcceptWith(*sock
, wait
))
1892 bool wxSocketServer::WaitForAccept(long seconds
, long milliseconds
)
1894 return DoWait(seconds
, milliseconds
, wxSOCKET_CONNECTION_FLAG
) == 1;
1897 wxSOCKET_T
wxSocketBase::GetSocket() const
1899 wxASSERT_MSG( m_impl
, wxS("Socket not initialised") );
1901 return m_impl
->m_fd
;
1905 bool wxSocketBase::GetOption(int level
, int optname
, void *optval
, int *optlen
)
1907 wxASSERT_MSG( m_impl
, wxT("Socket not initialised") );
1909 SOCKOPTLEN_T lenreal
= *optlen
;
1910 if ( getsockopt(m_impl
->m_fd
, level
, optname
,
1911 static_cast<char *>(optval
), &lenreal
) != 0 )
1920 wxSocketBase::SetOption(int level
, int optname
, const void *optval
, int optlen
)
1922 wxASSERT_MSG( m_impl
, wxT("Socket not initialised") );
1924 return setsockopt(m_impl
->m_fd
, level
, optname
,
1925 static_cast<const char *>(optval
), optlen
) == 0;
1928 bool wxSocketBase::SetLocal(const wxIPV4address
& local
)
1930 m_localAddress
= local
;
1935 // ==========================================================================
1937 // ==========================================================================
1939 // --------------------------------------------------------------------------
1941 // --------------------------------------------------------------------------
1943 wxSocketClient::wxSocketClient(wxSocketFlags flags
)
1944 : wxSocketBase(flags
, wxSOCKET_CLIENT
)
1946 m_initialRecvBufferSize
=
1947 m_initialSendBufferSize
= -1;
1950 // --------------------------------------------------------------------------
1952 // --------------------------------------------------------------------------
1954 bool wxSocketClient::DoConnect(const wxSockAddress
& remote
,
1955 const wxSockAddress
* local
,
1960 // Shutdown and destroy the old socket
1965 m_connected
= false;
1966 m_establishing
= false;
1968 // Create and set up the new one
1969 wxSocketManager
* const manager
= wxSocketManager::Get();
1970 m_impl
= manager
? manager
->CreateSocket(*this) : NULL
;
1974 // Reuse makes sense for clients too, if we are trying to rebind to the same port
1975 if (GetFlags() & wxSOCKET_REUSEADDR
)
1976 m_impl
->SetReusable();
1977 if (GetFlags() & wxSOCKET_BROADCAST
)
1978 m_impl
->SetBroadcast();
1979 if (GetFlags() & wxSOCKET_NOBIND
)
1980 m_impl
->DontDoBind();
1982 // Bind to the local IP address and port, when provided or if one had been
1984 if ( !local
&& m_localAddress
.GetAddress().IsOk() )
1985 local
= &m_localAddress
;
1988 m_impl
->SetLocal(local
->GetAddress());
1990 m_impl
->SetInitialSocketBuffers(m_initialRecvBufferSize
, m_initialSendBufferSize
);
1992 m_impl
->SetPeer(remote
.GetAddress());
1994 // Finally do create the socket and connect to the peer
1995 const wxSocketError err
= m_impl
->CreateClient(wait
);
1997 if ( err
!= wxSOCKET_NOERROR
)
1999 if ( err
== wxSOCKET_WOULDBLOCK
)
2001 wxASSERT_MSG( !wait
, "shouldn't get this for blocking connect" );
2003 m_establishing
= true;
2013 bool wxSocketClient::Connect(const wxSockAddress
& remote
, bool wait
)
2015 return DoConnect(remote
, NULL
, wait
);
2018 bool wxSocketClient::Connect(const wxSockAddress
& remote
,
2019 const wxSockAddress
& local
,
2022 return DoConnect(remote
, &local
, wait
);
2025 bool wxSocketClient::WaitOnConnect(long seconds
, long milliseconds
)
2029 // this happens if the initial attempt to connect succeeded without
2034 wxCHECK_MSG( m_establishing
&& m_impl
, false,
2035 "No connection establishment attempt in progress" );
2037 // notice that we return true even if DoWait() returned -1, i.e. if an
2038 // error occurred and connection was lost: this is intentional as we should
2039 // return false only if timeout expired without anything happening
2040 return DoWait(seconds
, milliseconds
, wxSOCKET_CONNECTION_FLAG
) != 0;
2043 // ==========================================================================
2045 // ==========================================================================
2047 wxDatagramSocket::wxDatagramSocket( const wxSockAddress
& addr
,
2048 wxSocketFlags flags
)
2049 : wxSocketBase( flags
, wxSOCKET_DATAGRAM
)
2051 // Create the socket
2052 wxSocketManager
* const manager
= wxSocketManager::Get();
2053 m_impl
= manager
? manager
->CreateSocket(*this) : NULL
;
2058 // Setup the socket as non connection oriented
2059 m_impl
->SetLocal(addr
.GetAddress());
2060 if (flags
& wxSOCKET_REUSEADDR
)
2062 m_impl
->SetReusable();
2064 if (GetFlags() & wxSOCKET_BROADCAST
)
2066 m_impl
->SetBroadcast();
2068 if (GetFlags() & wxSOCKET_NOBIND
)
2070 m_impl
->DontDoBind();
2073 if ( m_impl
->CreateUDP() != wxSOCKET_NOERROR
)
2079 // Initialize all stuff
2080 m_connected
= false;
2081 m_establishing
= false;
2084 wxDatagramSocket
& wxDatagramSocket::RecvFrom( wxSockAddress
& addr
,
2093 wxDatagramSocket
& wxDatagramSocket::SendTo( const wxSockAddress
& addr
,
2097 wxASSERT_MSG( m_impl
, wxT("Socket not initialised") );
2099 m_impl
->SetPeer(addr
.GetAddress());
2104 // ==========================================================================
2106 // ==========================================================================
2108 class wxSocketModule
: public wxModule
2111 virtual bool OnInit()
2113 // wxSocketBase will call Initialize() itself only if sockets are
2114 // really used, don't do it from here
2118 virtual void OnExit()
2120 if ( wxSocketBase::IsInitialized() )
2121 wxSocketBase::Shutdown();
2125 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
2128 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)
2130 #if defined(wxUSE_SELECT_DISPATCHER) && wxUSE_SELECT_DISPATCHER
2131 // NOTE: we need to force linking against socketiohandler.cpp otherwise in
2132 // static builds of wxWidgets the ManagerSetter::ManagerSetter ctor
2133 // contained there wouldn't be ever called
2134 wxFORCE_LINK_MODULE( socketiohandler
)
2137 // same for ManagerSetter in the MSW file
2139 wxFORCE_LINK_MODULE( mswsocket
)
2142 // and for OSXManagerSetter in the OS X one
2144 wxFORCE_LINK_MODULE( osxsocket
)
2147 #endif // wxUSE_SOCKETS