1 ////////////////////////////////////////////////////////////////////////////////
3 // Purpose: Socket handler classes
4 // Authors: Guilhem Lavaux (completely rewritten from a basic API of Andrew
5 // Davidson(1995) in wxWeb)
8 // Copyright: (C) 1998, 1997, Guilhem Lavaux
10 // License: see wxWindows license
11 ////////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "socket.h"
15 // #pragma implementation "socket.cpp"
19 typedef int socklen_t
;
22 // For compilers that support precompilation, includes "wx.h".
23 #include "wx/wxprec.h"
29 /////////////////////////////////////////////////////////////////////////////
31 /////////////////////////////////////////////////////////////////////////////
33 #include <wx/object.h>
34 #include <wx/string.h>
38 // Not enough OS behaviour defined for wxStubs
45 /////////////////////////////////////////////////////////////////////////////
46 // System specific headers
47 /////////////////////////////////////////////////////////////////////////////
49 // in order to avoid problems with our c library and double definitions
50 #define close closesocket
51 #define ioctl ioctlsocket
53 #include <wx/mac/macsock.h>
54 extern GUSISpinFn GUSISpin
;
55 #define PROCESS_EVENTS() wxMacProcessEvents()
56 const short kwxMacNetEventsMax
= 1000 ;
57 short wxMacNetEventsTop
= 0 ;
58 short wxMacNetEventsBottom
= 0 ;
59 short wxMacNetEventsEvents
[kwxMacNetEventsMax
] ;
60 void *wxMacNetEventsReferences
[kwxMacNetEventsMax
] ;
69 extern "C" void wxMacSocketHandlerProc( void *refcon
, short event
) ; // adds events
70 extern "C" void wxMacSocketOnRequestProc( void *refcon
, short event
) ; // consumes them
71 extern "C" void GUSISetReference( short sock
, short eventmask
, void * data
) ;
72 void wxMacProcessEvents() ;
75 #if defined(__WINDOWS__)
84 #include <sys/socket.h>
86 #include <sys/ioctl.h>
92 #include <sys/filio.h>
104 #if defined(__WXMOTIF__) || defined(__WXXT__)
105 #include <X11/Intrinsic.h>
107 /////////////////////////////
108 // Needs internal variables
109 /////////////////////////////
111 #define Uses_XtIntrinsic
116 #if defined(__WXGTK__)
120 /////////////////////////////////////////////////////////////////////////////
122 /////////////////////////////////////////////////////////////////////////////
123 #include "wx/module.h"
124 #define WXSOCK_INTERNAL
125 #include "wx/sckaddr.h"
126 #include "wx/socket.h"
128 /////////////////////////////////////////////////////////////////////////////
129 // Some patch ///// BEGIN
130 /////////////////////////////////////////////////////////////////////////////
132 #define close closesocket
133 #define ioctl ioctlsocket
137 #define errno WSAGetLastError()
141 #define EWOULDBLOCK WSAEWOULDBLOCK
142 #define ETIMEDOUT WSAETIMEDOUT
144 #define EINTR WSAEINTR
148 #define INVALID_SOCKET -1
152 #define wxAPP_CONTEXT ((XtAppContext)wxTheApp->GetAppContext())
156 // This is an MS TCP/IP routine and is not needed here. Some WinSock
157 // implementations (such as PC-NFS) will require you to include this
158 // or a similar routine (see appendix in WinSock doc or help file).
160 #if defined( NEED_WSAFDIsSet ) || defined( __VISUALC__ )
161 int PASCAL FAR
__WSAFDIsSet(SOCKET fd
, fd_set FAR
*set
)
163 int i
= set
->fd_count
;
167 if (set
->fd_array
[i
] == fd
)
176 #if defined(__WINDOWS__)
177 #define PROCESS_EVENTS() wxYield()
178 #elif defined(__WXXT__) || defined(__WXMOTIF__)
179 #define PROCESS_EVENTS() XtAppProcessEvent(wxAPP_CONTEXT, XtIMAll)
180 #elif defined(__WXGTK__)
181 #define PROCESS_EVENTS() gtk_main_iteration()
184 /////////////////////////////////////////////////////////////////////////////
185 // Some patch ///// END
186 /////////////////////////////////////////////////////////////////////////////
192 // --------------------------------------------------------------
194 // --------------------------------------------------------------
195 class wxSocketModule
: public wxModule
197 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
204 // --------------------------------------------------------------
206 // --------------------------------------------------------------
207 #if !USE_SHARED_LIBRARY
208 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
209 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
210 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
211 IMPLEMENT_CLASS(wxSocketHandler
, wxObject
)
212 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
213 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)
216 class wxSockWakeUp
: public wxTimer
223 wxSockWakeUp(wxSocketBase
*_sock
, int *id
, int new_val
)
225 my_id
= id
; n_val
= new_val
;
228 virtual void Notify()
231 if (sock
) sock
->Notify(FALSE
);
236 class SockRequest
: public wxObject
243 wxSockWakeUp
*auto_wakeup
;
244 wxSocketBase::wxRequestNotify type
;
248 /////////////////////////////////////////////////////////////////////////////
249 // Some internal define
250 /////////////////////////////////////////////////////////////////////////////
252 // --------------------------------------------------------------
253 // --------- wxSocketBase CONSTRUCTOR ---------------------------
254 // --------------------------------------------------------------
255 wxSocketBase::wxSocketBase(wxSocketBase::wxSockFlags _flags
,
256 wxSocketBase::wxSockType _type
) :
258 m_flags(_flags
), m_type(_type
), m_connected(FALSE
), m_connecting(FALSE
),
259 m_fd(INVALID_SOCKET
), m_waitflags(0), m_cbk(0), m_cdata(0), m_id(-1),
261 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
263 m_unread(NULL
), m_unrd_size(0),
265 m_timeout(3600), m_wantbuf(0)
267 m_internal
= new wxSockInternal
;
268 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
269 m_internal
->sock_inputid
= 0;
270 m_internal
->sock_outputid
= 0;
271 m_internal
->sock_exceptid
= 0;
274 m_internal
->my_msg
= 0;
278 wxSocketBase::wxSocketBase() :
280 m_flags(WAITALL
), m_type(SOCK_UNINIT
), m_connected(FALSE
),
281 m_connecting(FALSE
), m_fd(INVALID_SOCKET
), m_waitflags(0),
282 m_cbk(0), m_cdata(0),
283 m_id(-1), m_handler(0),
284 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
286 m_unread(NULL
), m_unrd_size(0),
288 m_timeout(3600), m_wantbuf(0)
290 m_internal
= new wxSockInternal
;
291 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
292 m_internal
->sock_inputid
= 0;
293 m_internal
->sock_outputid
= 0;
294 m_internal
->sock_exceptid
= 0;
297 m_internal
->my_msg
= 0;
301 // --------------------------------------------------------------
303 // --------------------------------------------------------------
305 wxSocketBase::~wxSocketBase()
315 if (m_internal
->my_msg
)
316 m_handler
->DestroyMessage(m_internal
->my_msg
);
318 m_handler
->UnRegister(this);
320 m_states
.DeleteContents(TRUE
);
325 bool wxSocketBase::Close()
327 if (m_fd
!= INVALID_SOCKET
)
329 for (int i
=0;i
<3;i
++)
331 wxNode
*n
, *node
= req_list
[i
].First();
335 SockRequest
*req
= (SockRequest
*)node
->Data();
347 m_fd
= INVALID_SOCKET
;
354 // --------------------------------------------------------------
355 // wxSocketBase base IO function
356 // --------------------------------------------------------------
358 wxSocketBase
& wxSocketBase::Read(char* buffer
, size_t nbytes
)
360 m_lcount
= GetPushback(buffer
, nbytes
, FALSE
);
362 // If we have got the whole needed buffer or if we don't want to
363 // wait then it returns immediately.
364 if (!nbytes
|| (m_lcount
&& !(m_flags
& WAITALL
)) )
367 WantBuffer(buffer
, nbytes
, EVT_READ
);
372 wxSocketBase
& wxSocketBase::Peek(char* buffer
, size_t nbytes
)
374 size_t nbytes_old
= nbytes
;
376 nbytes
-= GetPushback(buffer
, nbytes
, TRUE
);
379 m_lcount
= nbytes_old
;
383 WantBuffer(buffer
, nbytes
, EVT_PEEK
);
388 wxSocketBase
& wxSocketBase::Write(const char *buffer
, size_t nbytes
)
390 WantBuffer((char *)buffer
, nbytes
, EVT_WRITE
);
394 wxSocketBase
& wxSocketBase::ReadMsg(char* buffer
, size_t nbytes
)
397 size_t len
, len2
, sig
;
399 Read((char *)&msg
, sizeof(msg
));
400 if (m_lcount
!= sizeof(msg
))
403 sig
= msg
.sig
[0] & 0xff;
404 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
405 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
406 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
408 if (sig
!= 0xfeeddead)
410 len
= msg
.len
[0] & 0xff;
411 len
|= (size_t)(msg
.len
[1] & 0xff) << 8;
412 len
|= (size_t)(msg
.len
[2] & 0xff) << 16;
413 len
|= (size_t)(msg
.len
[3] & 0xff) << 24;
420 if (Read(buffer
, len
).LastCount() != len
)
422 if (len2
&& (Read(NULL
, len2
).LastCount() != len2
))
424 if (Read((char *)&msg
, sizeof(msg
)).LastCount() != sizeof(msg
))
427 sig
= msg
.sig
[0] & 0xff;
428 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
429 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
430 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
432 if (sig
!= 0xdeadfeed)
438 wxSocketBase
& wxSocketBase::WriteMsg(const char *buffer
, size_t nbytes
)
442 // warning about 'cast truncates constant value'
444 #pragma warning(disable: 4310)
445 #endif // __VISUALC__
447 msg
.sig
[0] = (char) 0xad;
448 msg
.sig
[1] = (char) 0xde;
449 msg
.sig
[2] = (char) 0xed;
450 msg
.sig
[3] = (char) 0xfe;
452 msg
.len
[0] = (char) nbytes
& 0xff;
453 msg
.len
[1] = (char) (nbytes
>> 8) & 0xff;
454 msg
.len
[2] = (char) (nbytes
>> 16) & 0xff;
455 msg
.len
[3] = (char) (nbytes
>> 24) & 0xff;
457 if (Write((char *)&msg
, sizeof(msg
)).LastCount() < sizeof(msg
))
459 if (Write(buffer
, nbytes
).LastCount() < nbytes
)
462 msg
.sig
[0] = (char) 0xed;
463 msg
.sig
[1] = (char) 0xfe;
464 msg
.sig
[2] = (char) 0xad;
465 msg
.sig
[3] = (char) 0xde;
466 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
467 Write((char *)&msg
, sizeof(msg
));
472 #pragma warning(default: 4310)
473 #endif // __VISUALC__
476 wxSocketBase
& wxSocketBase::Unread(const char *buffer
, size_t nbytes
)
478 CreatePushbackAfter(buffer
, nbytes
);
482 bool wxSocketBase::IsData() const
495 FD_SET(m_fd
, &sock_set
);
496 select(FD_SETSIZE
, &sock_set
, NULL
, NULL
, &tv
);
497 return (FD_ISSET(m_fd
, &sock_set
) != 0);
500 // ---------------------------------------------------------------------
501 // --------- wxSocketBase Discard(): deletes all byte in the input queue
502 // ---------------------------------------------------------------------
503 void wxSocketBase::Discard()
505 #define MAX_BUFSIZE (10*1024)
506 char *my_data
= new char[MAX_BUFSIZE
];
507 size_t recv_size
= MAX_BUFSIZE
;
510 SetFlags((wxSockFlags
)(NOWAIT
| SPEED
));
512 while (recv_size
== MAX_BUFSIZE
)
514 recv_size
= Read(my_data
, MAX_BUFSIZE
).LastCount();
523 // If what? Who seems to need unsigned int?
524 // BTW uint isn't even defined on wxMSW for VC++ for some reason. Even if it
525 // were, getpeername/getsockname don't take unsigned int*, they take int*.
527 // Under glibc 2.0.7, socketbits.h declares socklen_t to be unsigned int
528 // and it uses *socklen_t as the 3rd parameter. Robert.
530 // JACS - How can we detect this?
531 // Meanwhile, if your compiler complains about socklen_t,
532 // switch lines below.
535 # define wxSOCKET_INT socklen_t
537 # define wxSOCKET_INT int
540 // --------------------------------------------------------------
541 // wxSocketBase socket info functions
542 // --------------------------------------------------------------
544 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
546 struct sockaddr my_addr
;
547 wxSOCKET_INT len_addr
= sizeof(my_addr
);
552 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0)
555 addr_man
.Disassemble(&my_addr
, len_addr
);
559 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
561 struct sockaddr my_addr
;
562 wxSOCKET_INT len_addr
= sizeof(my_addr
);
567 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0)
571 addr_man
.Disassemble(&my_addr
, len_addr
);
575 // --------------------------------------------------------------
576 // wxSocketBase wait functions
577 // --------------------------------------------------------------
579 void wxSocketBase::SaveState()
581 wxSockState
*state
= new wxSockState
;
583 state
->cbk_on
= m_cbkon
;
584 state
->cbk_set
= m_neededreq
;
586 state
->cdata
= m_cdata
;
587 state
->flags
= m_flags
;
588 state
->notif
= m_notifyme
;
590 m_states
.Append(state
);
593 void wxSocketBase::RestoreState()
597 node
= m_states
.Last();
601 wxSockState
*state
= (wxSockState
*)node
->Data();
603 SetFlags(state
->flags
);
604 m_neededreq
= state
->cbk_set
;
606 m_cdata
= state
->cdata
;
607 m_notifyme
= state
->notif
;
617 // --------------------------------------------------------------
618 // --------- wxSocketBase wait functions ------------------------
619 // --------------------------------------------------------------
621 bool wxSocketBase::_Wait(long seconds
, long microseconds
, int type
)
623 if ((!m_connected
&& !m_connecting
) || m_fd
< 0)
626 wxSockWakeUp
wakeup(this, &m_waitflags
, 0);
629 SetNotify((wxRequestNotify
)type
);
633 wakeup
.Start((int)(seconds
*1000 + (microseconds
/ 1000)), TRUE
);
635 m_waitflags
= 0x80 | type
;
636 while (m_waitflags
& 0x80)
641 if (m_waitflags
& 0x40)
651 bool wxSocketBase::Wait(long seconds
, long microseconds
)
653 return _Wait(seconds
, microseconds
, REQ_ACCEPT
| REQ_CONNECT
|
654 REQ_READ
| REQ_WRITE
| REQ_LOST
);
657 bool wxSocketBase::WaitForRead(long seconds
, long microseconds
)
659 return _Wait(seconds
, microseconds
, REQ_READ
| REQ_LOST
);
662 bool wxSocketBase::WaitForWrite(long seconds
, long microseconds
)
664 return _Wait(seconds
, microseconds
, REQ_WRITE
);
667 bool wxSocketBase::WaitForLost(long seconds
, long microseconds
)
669 return _Wait(seconds
, microseconds
, REQ_LOST
);
672 // --------------------------------------------------------------
673 // --------- wxSocketBase callback management -------------------
674 // --------------------------------------------------------------
676 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
677 #if defined(__WXMOTIF__) || defined(__WXXT__)
678 static void wx_socket_read(XtPointer client
, int *fid
,
679 XtInputId
*WXUNUSED(id
))
682 static void wx_socket_read(gpointer client
, gint fd
,
683 GdkInputCondition
WXUNUSED(cond
))
687 wxSocketBase
*sock
= (wxSocketBase
*)client
;
691 i
= recv(fd
, &c
, 1, MSG_PEEK
);
693 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
))
695 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
701 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
706 sock
->OnRequest(wxSocketBase::EVT_READ
);
710 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
716 sock
->OnRequest(wxSocketBase::EVT_LOST
);
721 #if defined(__WXMOTIF__) || defined(__WXXT__)
722 static void wx_socket_write(XtPointer client
, int *WXUNUSED(fid
),
723 XtInputId
*WXUNUSED(id
))
725 static void wx_socket_write(gpointer client
, gint
WXUNUSED(fd
),
726 GdkInputCondition
WXUNUSED(cond
))
729 wxSocketBase
*sock
= (wxSocketBase
*)client
;
731 if (!sock
->IsConnected())
732 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
734 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
739 Notify_value
wx_sock_read_xview (Notify_client client
, int fd
)
741 wxSocketBase
*sock
= (wxSocketBase
*)client
;
745 i
= recv(fd
, &c
, 1, MSG_PEEK
);
747 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
))
749 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
756 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
757 return (Notify_value
) FALSE
;
759 sock
->OnRequest(wxSocketBase::EVT_READ
);
763 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
766 sock
->OnRequest(wxSocketBase::EVT_LOST
);
769 return (Notify_value
) FALSE
;
772 Notify_value
wx_sock_write_xview (Notify_client client
, int fd
)
774 wxSocketBase
*sock
= (wxSocketBase
*)client
;
776 if (!sock
->IsConnected())
777 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
779 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
781 return (Notify_value
) TRUE
;
785 wxSocketBase::wxRequestNotify
wxSocketBase::EventToNotify(wxRequestEvent evt
)
805 void wxSocketBase::SetFlags(wxSockFlags _flags
)
810 unsigned long flag
= 0;
811 ioctl(m_fd
, FIONBIO
, &flag
);
813 // SPEED and WAITALL are antagonists.
814 m_flags
= (wxSockFlags
)(m_flags
& ~WAITALL
);
820 unsigned long flag
= 1;
821 ioctl(m_fd
, FIONBIO
, &flag
);
825 void wxSocketBase::SetNotify(wxRequestNotify flags
)
827 wxRequestNotify old_needed_req
= m_neededreq
;
828 if (flags
& REQ_ACCEPT
)
830 /* Check if server */
831 if (!(GetClassInfo()->IsKindOf(CLASSINFO(wxSocketServer
))))
832 flags
&= ~REQ_ACCEPT
;
837 if (m_cbkon && old_needed_req != flags) seems to be wrong, Robert Roebling
841 if (old_needed_req
!= flags
)
845 void wxSocketBase::SetupCallbacks()
847 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| (m_flags
& SPEED
))
850 #if defined(__WXMOTIF__) || defined(__WXXT__)
851 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
))
853 if (m_internal
->sock_inputid
<= 0)
855 m_internal
->sock_inputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
856 (XtPointer
*) XtInputReadMask
,
857 (XtInputCallbackProc
) wx_socket_read
,
863 if (m_internal
->sock_inputid
> 0)
865 XtRemoveInput(m_internal
->sock_inputid
);
866 m_internal
->sock_inputid
= 0;
870 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
))
872 if (m_internal
->sock_outputid
<= 0)
874 m_internal
->sock_outputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
875 (XtPointer
*) XtInputWriteMask
,
876 (XtInputCallbackProc
) wx_socket_write
,
882 if (m_internal
->sock_outputid
> 0)
884 XtRemoveInput(m_internal
->sock_outputid
);
885 m_internal
->sock_outputid
= 0;
892 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
))
894 if (m_internal
->sock_inputid
<= 0)
896 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_READ
,
897 wx_socket_read
, (gpointer
)this);
902 if (m_internal
->sock_inputid
> 0)
905 gdk_input_remove(m_internal->sock_inputid);
906 m_internal->sock_inputid = 0;
911 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
))
913 if (m_internal
->sock_outputid
<= 0)
915 m_internal
->sock_outputid
= gdk_input_add(m_fd
, GDK_INPUT_WRITE
,
916 wx_socket_write
, (gpointer
)this);
921 if (m_internal
->sock_outputid
> 0)
924 gdk_input_remove(m_internal->sock_outputid);
925 m_internal->sock_outputid = 0;
935 if (m_neededreq
& REQ_READ
)
937 if (m_neededreq
& REQ_WRITE
)
939 if (m_neededreq
& REQ_LOST
)
941 if (m_neededreq
& REQ_ACCEPT
)
943 if (m_neededreq
& REQ_CONNECT
)
946 if (!m_internal
->my_msg
)
947 m_internal
->my_msg
= m_handler
->NewMessage(this);
948 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), m_internal
->my_msg
, mask
);
953 if (m_neededreq
& REQ_READ
)
955 if (m_neededreq
& REQ_WRITE
)
957 if (m_neededreq
& REQ_LOST
)
959 if (m_neededreq
& REQ_ACCEPT
)
961 if (m_neededreq
& REQ_CONNECT
)
964 GUSISetReference( m_fd
,mask
, this ) ;
965 unsigned long flag
= 1;
966 ioctl(m_fd
, FIONBIO
, &flag
);
969 m_processing
= FALSE
;
972 void wxSocketBase::DestroyCallbacks()
974 if (!m_cbkon
|| !m_handler
)
978 m_processing
= FALSE
;
979 #if defined(__WXMOTIF__) || defined(__WXXT__)
980 if (m_internal
->sock_inputid
> 0)
981 XtRemoveInput(m_internal
->sock_inputid
);
982 m_internal
->sock_inputid
= 0;
983 if (m_internal
->sock_outputid
> 0)
984 XtRemoveInput(m_internal
->sock_outputid
);
985 m_internal
->sock_outputid
= 0;
988 if (m_internal
->sock_inputid
> 0)
989 gdk_input_remove(m_internal
->sock_inputid
);
990 m_internal
->sock_inputid
= 0;
991 if (m_internal
->sock_outputid
> 0)
992 gdk_input_remove(m_internal
->sock_outputid
);
993 m_internal
->sock_outputid
= 0;
996 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), 0, 0);
999 GUSISetReference( m_fd
, 0 , 0 ) ;
1000 int bottom
= wxMacNetEventsBottom
;
1001 while ( wxMacNetEventsTop
!= bottom
)
1003 // set all events that reference this socket to nil
1004 if ( wxMacNetEventsReferences
[bottom
] == (void*) this )
1005 wxMacNetEventsReferences
[bottom
] = NULL
;
1007 if ( bottom
== kwxMacNetEventsMax
)
1010 SetFlags( m_flags
) ;
1014 void wxSocketBase::Notify(bool notify
)
1016 if (m_notifyme
== notify
)
1022 m_notifyme
= notify
;
1025 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
1027 wxRequestNotify req_notif
= EventToNotify(req_evt
);
1029 // Mask the current event
1030 SetNotify(m_neededreq
& ~req_notif
);
1032 if (req_evt
<= EVT_WRITE
&& DoRequests(req_evt
))
1035 if (m_waitflags
& 0xF0)
1038 if ((m_waitflags
& 0x0F) == req_evt
)
1048 if (req_evt
== EVT_LOST
)
1050 m_connected
= FALSE
;
1054 OldOnNotify(req_evt
);
1057 SetNotify(m_neededreq
| req_notif
);
1060 wxSocketEvent::wxSocketEvent(int id
)
1063 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
1068 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
1070 wxSocketEvent
event(m_id
);
1072 event
.SetEventObject(this);
1073 event
.m_skevt
= evt
;
1074 ProcessEvent(event
);
1077 m_cbk(*this, evt
, m_cdata
);
1080 // --------------------------------------------------------------
1081 // --------- wxSocketBase functions [Callback, CallbackData] ----
1082 // --------------------------------------------------------------
1084 wxSocketBase::wxSockCbk
wxSocketBase::Callback(wxSocketBase::wxSockCbk _cbk
)
1086 wxSockCbk old_cbk
= m_cbk
;
1092 char *wxSocketBase::CallbackData(char *cdata_
)
1094 char *old_cdata
= m_cdata
;
1100 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
1102 SetNextHandler(&h_evt
);
1106 // --------------------------------------------------------------
1107 // --------- wxSocketBase pushback library ----------------------
1108 // --------------------------------------------------------------
1110 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
1114 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
1115 curr_pos
= m_unread
+ m_unrd_size
;
1117 memcpy(curr_pos
, buffer
, size
);
1118 m_unrd_size
+= size
;
1121 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
1123 char *curr_pos
, *new_buf
;
1125 new_buf
= (char *) malloc(m_unrd_size
+size
);
1126 curr_pos
= new_buf
+ size
;
1128 memcpy(new_buf
, buffer
, size
);
1129 memcpy(curr_pos
, m_unread
, m_unrd_size
);
1133 m_unrd_size
+= size
;
1136 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
1141 if (size
> m_unrd_size
)
1143 memcpy(buffer
, m_unread
, size
);
1146 m_unrd_size
-= size
;
1156 // --------------------------------------------------------------
1157 // --------- wxSocketBase "multi-thread" core -------------------
1158 // --------------------------------------------------------------
1160 bool wxSocketBase::DoRequests(wxRequestEvent req_flag
)
1162 wxNode
*node
= req_list
[req_flag
].First();
1169 SockRequest
*req
= (SockRequest
*)node
->Data();
1177 ret
= recv(m_fd
, req
->buffer
, req
->size
,
1178 (req
->type
== EVT_PEEK
) ? MSG_PEEK
: 0);
1186 if ((len
< req
->size
) && (m_flags
& WAITALL
))
1191 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1192 req_list
[req_flag
].Insert(req
);
1202 ret
= send(m_fd
, req
->buffer
, req
->size
, 0);
1210 if ((len
< req
->size
) && (m_flags
& WAITALL
))
1215 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1216 req_list
[req_flag
].Insert(req
);
1231 void wxSocketBase::WantSpeedBuffer(char *buffer
, size_t nbytes
,
1240 ret
= recv(m_fd
, buffer
, nbytes
,
1241 (evt
== EVT_PEEK
) ? MSG_PEEK
: 0);
1244 ret
= send(m_fd
, buffer
, nbytes
, 0);
1259 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
1264 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
1267 if (m_flags
& SPEED
)
1269 WantSpeedBuffer(buffer
, nbytes
, evt
);
1273 SockRequest
*buf
= new SockRequest
;
1274 wxSockWakeUp
s_wake(NULL
, (int *)&buf_timed_out
, (int)TRUE
);
1277 req_list
[evt
].Append(buf
);
1280 SetNotify(REQ_LOST
| EventToNotify(evt
));
1282 buf
->buffer
= buffer
;
1287 buf
->auto_wakeup
= &s_wake
;
1289 buf_timed_out
= FALSE
;
1291 s_wake
.Start(m_timeout
*1000, TRUE
);
1292 if (m_flags
& NOWAIT
)
1298 while (!buf
->done
&& !buf_timed_out
)
1302 m_lcount
= buf
->nbytes
;
1304 m_error
= ETIMEDOUT
;
1306 m_error
= buf
->error
;
1312 // --------------------------------------------------------------
1314 // --------------------------------------------------------------
1316 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1317 wxSockFlags flags
) :
1318 wxSocketBase(flags
, SOCK_SERVER
)
1320 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1322 if (m_fd
== INVALID_SOCKET
)
1326 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
1328 struct sockaddr
*myaddr
;
1331 addr_man
.Build(myaddr
, len
);
1332 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
1335 if (listen(m_fd
, 5) < 0) {
1336 m_fd
= INVALID_SOCKET
;
1341 // --------------------------------------------------------------
1342 // wxSocketServer Accept
1343 // --------------------------------------------------------------
1345 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
1349 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
1352 struct linger linger
;
1354 linger
.l_linger
= 1;
1356 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1359 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1361 if (!(sock
.m_flags
& SPEED
))
1363 unsigned long flag2
= 1;
1364 ioctl(fd2
, FIONBIO
, &flag2
);
1367 sock
.m_type
= SOCK_INTERNAL
;
1369 sock
.m_connected
= TRUE
;
1374 wxSocketBase
*wxSocketServer::Accept()
1376 wxSocketBase
* sock
= new wxSocketBase();
1378 sock
->SetFlags((wxSockFlags
)m_flags
);
1380 if (!AcceptWith(*sock
))
1384 m_handler
->Register(sock
);
1389 // --------------------------------------------------------------
1390 // wxSocketServer callbacks
1391 // --------------------------------------------------------------
1393 void wxSocketServer::OnRequest(wxRequestEvent evt
)
1395 if (evt
== EVT_ACCEPT
)
1397 OldOnNotify(EVT_ACCEPT
);
1401 // --------------------------------------------------------------
1403 // --------------------------------------------------------------
1405 // --------- wxSocketClient CONSTRUCTOR -------------------------
1406 // --------------------------------------------------------------
1407 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
1408 wxSocketBase(_flags
, SOCK_CLIENT
)
1412 // --------------------------------------------------------------
1413 // --------- wxSocketClient DESTRUCTOR --------------------------
1414 // --------------------------------------------------------------
1415 wxSocketClient::~wxSocketClient()
1419 // --------------------------------------------------------------
1420 // --------- wxSocketClient Connect functions -------------------
1421 // --------------------------------------------------------------
1422 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
1424 struct linger linger
;
1429 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1434 m_connected
= FALSE
;
1437 linger
.l_linger
= 5;
1438 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1440 // Stay in touch with the state of things...
1442 unsigned long flag
= 1;
1443 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1445 // Disable the nagle algorithm, which delays sends till the
1446 // buffer is full (or a certain time period has passed?)...
1448 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1450 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
1453 struct sockaddr
*remote
;
1456 addr_man
.Build(remote
, len
);
1458 if (connect(m_fd
, remote
, len
) != 0)
1461 if (!(m_flags
& SPEED
))
1464 ioctl(m_fd
, FIONBIO
, &flag
);
1473 bool wxSocketClient::WaitOnConnect(long seconds
, long microseconds
)
1475 int ret
= _Wait(seconds
, microseconds
, REQ_CONNECT
| REQ_LOST
);
1483 void wxSocketClient::OnRequest(wxRequestEvent evt
)
1485 if (evt
== EVT_CONNECT
)
1490 SetNotify(m_neededreq
& ~REQ_CONNECT
);
1496 OldOnNotify(EVT_CONNECT
);
1502 wxSocketBase::OnRequest(evt
);
1505 /////////////////////////////////////////////////////////////////
1506 // wxSocketHandler ///////////////////////////////////////////////
1507 /////////////////////////////////////////////////////////////////
1509 wxSocketHandler
*wxSocketHandler::master
= NULL
;
1510 #if defined(__WINDOWS__)
1511 static int win_initialized
= 0;
1514 // --------------------------------------------------------------
1515 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1516 // --------------------------------------------------------------
1519 extern "C" int updatestatus(int s
) ;
1521 void wxMacSocketOnRequestProc( void *refcon
, short event
)
1525 wxSocketBase
*sock
= (wxSocketBase
*) refcon
;
1527 wxSocketBase::wxRequestEvent sk_req
;
1535 sk_req
= wxSocketBase::EVT_READ
;
1536 sock
->OnRequest(sk_req
);
1539 sk_req
= wxSocketBase::EVT_WRITE
;
1540 sock
->OnRequest(sk_req
);
1543 sk_req
= wxSocketBase::EVT_LOST
;
1544 sock
->OnRequest(sk_req
);
1547 sk_req
= wxSocketBase::EVT_ACCEPT
;
1548 sock
->OnRequest(sk_req
);
1551 sk_req
= wxSocketBase::EVT_CONNECT
;
1552 sock
->OnRequest(sk_req
);
1557 updatestatus ( sock
->m_fd
) ;
1561 void wxMacSocketHandlerProc( void *refcon
, short event
)
1563 wxMacNetEventsReferences
[wxMacNetEventsTop
] = refcon
;
1564 wxMacNetEventsEvents
[wxMacNetEventsTop
] = event
;
1566 // clumsy construct in order to never have a incorrect wxMacNetEventsTop (above limits)
1568 if ( wxMacNetEventsTop
+ 1 == kwxMacNetEventsMax
)
1569 wxMacNetEventsTop
= 0 ;
1571 wxMacNetEventsTop
++ ;
1577 extern char wxPanelClassName
[];
1579 LRESULT APIENTRY _EXPORT
wxSocketHandlerWndProc(HWND hWnd
, UINT message
,
1580 WPARAM wParam
, LPARAM lParam
)
1582 if(message
==WM_DESTROY
)
1584 ::SetWindowLong(hWnd
, GWL_WNDPROC
, (LONG
) DefWindowProc
);
1585 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1587 wxSocketHandler
*h_sock
= (wxSocketHandler
*)GetWindowLong(hWnd
, GWL_USERDATA
);
1588 wxNode
*node
= h_sock
->smsg_list
->Find(message
);
1590 wxSocketBase::wxRequestEvent sk_req
;
1591 UINT event
= WSAGETSELECTEVENT(lParam
);
1594 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1596 sock
= (wxSocketBase
*)node
->Data();
1600 sk_req
= wxSocketBase::EVT_READ
;
1603 sk_req
= wxSocketBase::EVT_WRITE
;
1606 sk_req
= wxSocketBase::EVT_LOST
;
1609 sk_req
= wxSocketBase::EVT_ACCEPT
;
1612 sk_req
= wxSocketBase::EVT_CONNECT
;
1616 wxFAIL_MSG("invalid socket event");
1620 sock
->OnRequest(sk_req
);
1625 FARPROC wxSocketSubClassProc
= NULL
;
1629 wxSocketHandler::wxSocketHandler()
1631 #if defined(__WINDOWS__)
1632 if (!win_initialized
)
1636 WSAStartup((1 << 8) | 1, &wsaData
);
1637 win_initialized
= 1;
1639 internal
= new wxSockHandlerInternal
;
1640 internal
->sockWin
= ::CreateWindow(wxPanelClassName
, NULL
, 0,
1641 0, 0, 0, 0, NULL
, (HMENU
) NULL
,
1644 // Subclass the window
1645 if (!wxSocketSubClassProc
)
1646 wxSocketSubClassProc
= MakeProcInstance((FARPROC
) wxSocketHandlerWndProc
, wxhInstance
);
1647 ::SetWindowLong(internal
->sockWin
, GWL_WNDPROC
, (LONG
) wxSocketSubClassProc
);
1648 ::SetWindowLong(internal
->sockWin
, GWL_USERDATA
, (LONG
) this);
1650 internal
->firstAvailableMsg
= 5000;
1651 smsg_list
= new wxList(wxKEY_INTEGER
);
1657 signal(SIGPIPE
, SIG_IGN
);
1661 // --------------------------------------------------------------
1662 // --------- wxSocketHandler DESTRUCTOR -------------------------
1663 // --------------------------------------------------------------
1664 wxSocketHandler::~wxSocketHandler()
1666 wxNode
*next_node
, *node
= socks
->First();
1670 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
1673 next_node
= node
->Next();
1683 ::DestroyWindow(internal
->sockWin
);
1685 win_initialized
= 0;
1691 // --------------------------------------------------------------
1692 // --------- wxSocketHandler registering functions --------------
1693 // --------------------------------------------------------------
1695 void wxSocketHandler::Register(wxSocketBase
* sock
)
1699 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next())
1701 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1709 socks
->Append(sock
);
1710 sock
->SetHandler(this);
1711 sock
->SetupCallbacks();
1715 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
1719 for (node
= socks
->First(); node
; node
= node
->Next())
1721 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1726 sock
->DestroyCallbacks();
1727 sock
->SetHandler(NULL
);
1733 unsigned long wxSocketHandler::Count() const
1735 return socks
->Number();
1738 // --------------------------------------------------------------
1739 // --------- wxSocketHandler "big" wait functions ---------------
1740 // --------------------------------------------------------------
1741 void handler_cbk(wxSocketBase
& sock
,
1742 wxSocketBase::wxRequestEvent
WXUNUSED(flags
),
1745 int *a_wait
= (int *)cdata
;
1751 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1755 wxSockWakeUp
s_wake(NULL
, &on_wait
, -2);
1758 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++)
1760 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1764 sock
->SetupCallbacks();
1766 sock
->Callback(handler_cbk
);
1767 sock
->CallbackData((char *)&on_wait
);
1771 s_wake
.Start((seconds
*1000) + (microseconds
/1000), TRUE
);
1776 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++)
1778 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1780 sock
->RestoreState();
1789 void wxSocketHandler::YieldSock()
1793 for (node
= socks
->First(); node
; node
= node
->Next() )
1795 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1799 sock
->SetFlags(wxSocketBase::SPEED
);
1801 sock
->DoRequests(wxSocketBase::EVT_READ
);
1802 sock
->DoRequests(wxSocketBase::EVT_WRITE
);
1804 sock
->RestoreState();
1808 // --------------------------------------------------------------
1809 // --------- wxSocketHandler: create and register the socket ----
1810 // --------------------------------------------------------------
1811 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1812 wxSocketBase::wxSockFlags flags
)
1814 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1820 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1822 wxSocketClient
*client
= new wxSocketClient(flags
);
1829 // --------------------------------------------------------------
1830 // --------- wxSocketHandler: Windows specific methods ----------
1831 // --------------------------------------------------------------
1833 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1835 internal
->firstAvailableMsg
++;
1836 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1837 return internal
->firstAvailableMsg
;
1840 void wxSocketHandler::DestroyMessage(UINT msg
)
1842 wxNode
*node
= smsg_list
->Find(msg
);
1846 HWND
wxSocketHandler::GetHWND() const
1848 return internal
->sockWin
;
1853 bool wxSocketModule::OnInit()
1855 wxSocketHandler::master
= new wxSocketHandler();
1859 void wxSocketModule::OnExit()
1861 delete wxSocketHandler::master
;
1862 wxSocketHandler::master
= NULL
;
1866 void wxMacProcessSocketEvents() ;
1867 void wxMacProcessEvents()
1869 wxMacProcessSocketEvents() ;
1870 (*GUSISpin
)(SP_MISC
, 0) ;
1873 void wxMacProcessSocketEvents()
1875 while ( wxMacNetEventsTop
!= wxMacNetEventsBottom
)
1877 // consume event at wxMacNetEventsBottom
1878 wxMacSocketOnRequestProc(wxMacNetEventsReferences
[wxMacNetEventsBottom
] , wxMacNetEventsEvents
[wxMacNetEventsBottom
] ) ;
1879 wxMacNetEventsBottom
++ ;
1880 if ( wxMacNetEventsBottom
== kwxMacNetEventsMax
)
1881 wxMacNetEventsBottom
= 0 ;