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( _MSC_VER )
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 /////////////////////////////////////////////////////////////////////////////
188 // --------------------------------------------------------------
190 // --------------------------------------------------------------
191 class wxSocketModule
: public wxModule
193 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
200 // --------------------------------------------------------------
202 // --------------------------------------------------------------
203 #if !USE_SHARED_LIBRARY
204 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
205 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
206 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
207 IMPLEMENT_CLASS(wxSocketHandler
, wxObject
)
208 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
209 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)
212 class wxSockWakeUp
: public wxTimer
219 wxSockWakeUp(wxSocketBase
*_sock
, int *id
, int new_val
)
221 my_id
= id
; n_val
= new_val
;
224 virtual void Notify()
227 if (sock
) sock
->Notify(FALSE
);
232 class SockRequest
: public wxObject
239 wxSockWakeUp
*auto_wakeup
;
240 wxSocketBase::wxRequestNotify type
;
244 /////////////////////////////////////////////////////////////////////////////
245 // Some internal define
246 /////////////////////////////////////////////////////////////////////////////
248 // --------------------------------------------------------------
249 // --------- wxSocketBase CONSTRUCTOR ---------------------------
250 // --------------------------------------------------------------
251 wxSocketBase::wxSocketBase(wxSocketBase::wxSockFlags _flags
,
252 wxSocketBase::wxSockType _type
) :
254 m_flags(_flags
), m_type(_type
), m_connected(FALSE
), m_connecting(FALSE
),
255 m_fd(INVALID_SOCKET
), m_waitflags(0), m_cbk(0), m_cdata(0), m_id(-1),
257 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
259 m_unread(NULL
), m_unrd_size(0),
261 m_timeout(3600), m_wantbuf(0)
263 m_internal
= new wxSockInternal
;
264 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
265 m_internal
->sock_inputid
= 0;
266 m_internal
->sock_outputid
= 0;
267 m_internal
->sock_exceptid
= 0;
270 m_internal
->my_msg
= 0;
274 wxSocketBase::wxSocketBase() :
276 m_flags(WAITALL
), m_type(SOCK_UNINIT
), m_connected(FALSE
),
277 m_connecting(FALSE
), m_fd(INVALID_SOCKET
), m_waitflags(0),
278 m_cbk(0), m_cdata(0),
279 m_id(-1), m_handler(0),
280 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
282 m_unread(NULL
), m_unrd_size(0),
284 m_timeout(3600), m_wantbuf(0)
286 m_internal
= new wxSockInternal
;
287 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
288 m_internal
->sock_inputid
= 0;
289 m_internal
->sock_outputid
= 0;
290 m_internal
->sock_exceptid
= 0;
293 m_internal
->my_msg
= 0;
297 // --------------------------------------------------------------
299 // --------------------------------------------------------------
301 wxSocketBase::~wxSocketBase()
311 if (m_internal
->my_msg
)
312 m_handler
->DestroyMessage(m_internal
->my_msg
);
314 m_handler
->UnRegister(this);
316 m_states
.DeleteContents(TRUE
);
321 bool wxSocketBase::Close()
323 if (m_fd
!= INVALID_SOCKET
)
325 for (int i
=0;i
<3;i
++)
327 wxNode
*n
, *node
= req_list
[i
].First();
331 SockRequest
*req
= (SockRequest
*)node
->Data();
343 m_fd
= INVALID_SOCKET
;
350 // --------------------------------------------------------------
351 // wxSocketBase base IO function
352 // --------------------------------------------------------------
354 wxSocketBase
& wxSocketBase::Read(char* buffer
, size_t nbytes
)
356 m_lcount
= GetPushback(buffer
, nbytes
, FALSE
);
358 // If we have got the whole needed buffer or if we don't want to
359 // wait then it returns immediately.
360 if (!nbytes
|| (m_lcount
&& !(m_flags
& WAITALL
)) )
363 WantBuffer(buffer
, nbytes
, EVT_READ
);
368 wxSocketBase
& wxSocketBase::Peek(char* buffer
, size_t nbytes
)
370 size_t nbytes_old
= nbytes
;
372 nbytes
-= GetPushback(buffer
, nbytes
, TRUE
);
375 m_lcount
= nbytes_old
;
379 WantBuffer(buffer
, nbytes
, EVT_PEEK
);
384 wxSocketBase
& wxSocketBase::Write(const char *buffer
, size_t nbytes
)
386 WantBuffer((char *)buffer
, nbytes
, EVT_WRITE
);
390 wxSocketBase
& wxSocketBase::ReadMsg(char* buffer
, size_t nbytes
)
393 size_t len
, len2
, sig
;
395 Read((char *)&msg
, sizeof(msg
));
396 if (m_lcount
!= sizeof(msg
))
399 sig
= msg
.sig
[0] & 0xff;
400 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
401 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
402 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
404 if (sig
!= 0xfeeddead)
406 len
= msg
.len
[0] & 0xff;
407 len
|= (size_t)(msg
.len
[1] & 0xff) << 8;
408 len
|= (size_t)(msg
.len
[2] & 0xff) << 16;
409 len
|= (size_t)(msg
.len
[3] & 0xff) << 24;
416 if (Read(buffer
, len
).LastCount() != len
)
418 if (len2
&& (Read(NULL
, len2
).LastCount() != len2
))
420 if (Read((char *)&msg
, sizeof(msg
)).LastCount() != sizeof(msg
))
423 sig
= msg
.sig
[0] & 0xff;
424 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
425 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
426 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
428 if (sig
!= 0xdeadfeed)
434 wxSocketBase
& wxSocketBase::WriteMsg(const char *buffer
, size_t nbytes
)
438 msg
.sig
[0] = (char) 0xad;
439 msg
.sig
[1] = (char) 0xde;
440 msg
.sig
[2] = (char) 0xed;
441 msg
.sig
[3] = (char) 0xfe;
443 msg
.len
[0] = (char) nbytes
& 0xff;
444 msg
.len
[1] = (char) (nbytes
>> 8) & 0xff;
445 msg
.len
[2] = (char) (nbytes
>> 16) & 0xff;
446 msg
.len
[3] = (char) (nbytes
>> 24) & 0xff;
448 if (Write((char *)&msg
, sizeof(msg
)).LastCount() < sizeof(msg
))
450 if (Write(buffer
, nbytes
).LastCount() < nbytes
)
453 msg
.sig
[0] = (char) 0xed;
454 msg
.sig
[1] = (char) 0xfe;
455 msg
.sig
[2] = (char) 0xad;
456 msg
.sig
[3] = (char) 0xde;
457 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
458 Write((char *)&msg
, sizeof(msg
));
463 wxSocketBase
& wxSocketBase::Unread(const char *buffer
, size_t nbytes
)
465 CreatePushbackAfter(buffer
, nbytes
);
469 bool wxSocketBase::IsData() const
482 FD_SET(m_fd
, &sock_set
);
483 select(FD_SETSIZE
, &sock_set
, NULL
, NULL
, &tv
);
484 return (FD_ISSET(m_fd
, &sock_set
) != 0);
487 // ---------------------------------------------------------------------
488 // --------- wxSocketBase Discard(): deletes all byte in the input queue
489 // ---------------------------------------------------------------------
490 void wxSocketBase::Discard()
492 #define MAX_BUFSIZE (10*1024)
493 char *my_data
= new char[MAX_BUFSIZE
];
494 size_t recv_size
= MAX_BUFSIZE
;
497 SetFlags((wxSockFlags
)(NOWAIT
| SPEED
));
499 while (recv_size
== MAX_BUFSIZE
)
501 recv_size
= Read(my_data
, MAX_BUFSIZE
).LastCount();
510 // If what? Who seems to need unsigned int?
511 // BTW uint isn't even defined on wxMSW for VC++ for some reason. Even if it
512 // were, getpeername/getsockname don't take unsigned int*, they take int*.
514 #define wxSOCKET_INT unsigned int
516 #define wxSOCKET_INT int
519 // --------------------------------------------------------------
520 // wxSocketBase socket info functions
521 // --------------------------------------------------------------
523 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
525 struct sockaddr my_addr
;
526 wxSOCKET_INT len_addr
= sizeof(my_addr
);
531 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0)
534 addr_man
.Disassemble(&my_addr
, len_addr
);
538 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
540 struct sockaddr my_addr
;
541 wxSOCKET_INT len_addr
= sizeof(my_addr
);
546 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0)
550 addr_man
.Disassemble(&my_addr
, len_addr
);
554 // --------------------------------------------------------------
555 // wxSocketBase wait functions
556 // --------------------------------------------------------------
558 void wxSocketBase::SaveState()
560 wxSockState
*state
= new wxSockState
;
562 state
->cbk_on
= m_cbkon
;
563 state
->cbk_set
= m_neededreq
;
565 state
->cdata
= m_cdata
;
566 state
->flags
= m_flags
;
567 state
->notif
= m_notifyme
;
569 m_states
.Append(state
);
572 void wxSocketBase::RestoreState()
576 node
= m_states
.Last();
580 wxSockState
*state
= (wxSockState
*)node
->Data();
582 SetFlags(state
->flags
);
583 m_neededreq
= state
->cbk_set
;
585 m_cdata
= state
->cdata
;
586 m_notifyme
= state
->notif
;
596 // --------------------------------------------------------------
597 // --------- wxSocketBase wait functions ------------------------
598 // --------------------------------------------------------------
600 bool wxSocketBase::_Wait(long seconds
, long microseconds
, int type
)
602 if ((!m_connected
&& !m_connecting
) || m_fd
< 0)
605 wxSockWakeUp
wakeup(this, &m_waitflags
, 0);
608 SetNotify((wxRequestNotify
)type
);
612 wakeup
.Start((int)(seconds
*1000 + (microseconds
/ 1000)), TRUE
);
614 m_waitflags
= 0x80 | type
;
615 while (m_waitflags
& 0x80)
620 if (m_waitflags
& 0x40)
630 bool wxSocketBase::Wait(long seconds
, long microseconds
)
632 return _Wait(seconds
, microseconds
, REQ_ACCEPT
| REQ_CONNECT
|
633 REQ_READ
| REQ_WRITE
| REQ_LOST
);
636 bool wxSocketBase::WaitForRead(long seconds
, long microseconds
)
638 return _Wait(seconds
, microseconds
, REQ_READ
| REQ_LOST
);
641 bool wxSocketBase::WaitForWrite(long seconds
, long microseconds
)
643 return _Wait(seconds
, microseconds
, REQ_WRITE
);
646 bool wxSocketBase::WaitForLost(long seconds
, long microseconds
)
648 return _Wait(seconds
, microseconds
, REQ_LOST
);
651 // --------------------------------------------------------------
652 // --------- wxSocketBase callback management -------------------
653 // --------------------------------------------------------------
655 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
656 #if defined(__WXMOTIF__) || defined(__WXXT__)
657 static void wx_socket_read(XtPointer client
, int *fid
,
658 XtInputId
*WXUNUSED(id
))
661 static void wx_socket_read(gpointer client
, gint fd
,
662 GdkInputCondition
WXUNUSED(cond
))
666 wxSocketBase
*sock
= (wxSocketBase
*)client
;
670 i
= recv(fd
, &c
, 1, MSG_PEEK
);
672 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
))
674 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
680 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
685 sock
->OnRequest(wxSocketBase::EVT_READ
);
689 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
695 sock
->OnRequest(wxSocketBase::EVT_LOST
);
700 #if defined(__WXMOTIF__) || defined(__WXXT__)
701 static void wx_socket_write(XtPointer client
, int *WXUNUSED(fid
),
702 XtInputId
*WXUNUSED(id
))
704 static void wx_socket_write(gpointer client
, gint
WXUNUSED(fd
),
705 GdkInputCondition
WXUNUSED(cond
))
708 wxSocketBase
*sock
= (wxSocketBase
*)client
;
710 if (!sock
->IsConnected())
711 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
713 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
718 Notify_value
wx_sock_read_xview (Notify_client client
, int fd
)
720 wxSocketBase
*sock
= (wxSocketBase
*)client
;
724 i
= recv(fd
, &c
, 1, MSG_PEEK
);
726 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
))
728 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
735 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
736 return (Notify_value
) FALSE
;
738 sock
->OnRequest(wxSocketBase::EVT_READ
);
742 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
745 sock
->OnRequest(wxSocketBase::EVT_LOST
);
748 return (Notify_value
) FALSE
;
751 Notify_value
wx_sock_write_xview (Notify_client client
, int fd
)
753 wxSocketBase
*sock
= (wxSocketBase
*)client
;
755 if (!sock
->IsConnected())
756 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
758 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
760 return (Notify_value
) TRUE
;
764 wxSocketBase::wxRequestNotify
wxSocketBase::EventToNotify(wxRequestEvent evt
)
784 void wxSocketBase::SetFlags(wxSockFlags _flags
)
789 unsigned long flag
= 0;
790 ioctl(m_fd
, FIONBIO
, &flag
);
792 // SPEED and WAITALL are antagonists.
793 m_flags
= (wxSockFlags
)(m_flags
& ~WAITALL
);
799 unsigned long flag
= 1;
800 ioctl(m_fd
, FIONBIO
, &flag
);
804 void wxSocketBase::SetNotify(wxRequestNotify flags
)
806 wxRequestNotify old_needed_req
= m_neededreq
;
807 if (flags
& REQ_ACCEPT
)
809 /* Check if server */
810 if (!(GetClassInfo()->IsKindOf(CLASSINFO(wxSocketServer
))))
811 flags
&= ~REQ_ACCEPT
;
816 if (m_cbkon && old_needed_req != flags) seems to be wrong, Robert Roebling
820 if (old_needed_req
!= flags
)
824 void wxSocketBase::SetupCallbacks()
826 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| (m_flags
& SPEED
))
829 #if defined(__WXMOTIF__) || defined(__WXXT__)
830 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
))
832 if (m_internal
->sock_inputid
<= 0)
834 m_internal
->sock_inputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
835 (XtPointer
*) XtInputReadMask
,
836 (XtInputCallbackProc
) wx_socket_read
,
841 if (m_internal
->sock_inputid
> 0)
843 XtRemoveInput(m_internal
->sock_inputid
);
844 m_internal
->sock_inputid
= 0;
848 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
))
850 if (m_internal
->sock_outputid
<= 0)
852 m_internal
->sock_outputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
853 (XtPointer
*) XtInputWriteMask
,
854 (XtInputCallbackProc
) wx_socket_write
,
860 if (m_internal
->sock_outputid
> 0)
862 XtRemoveInput(m_internal
->sock_outputid
);
863 m_internal
->sock_outputid
= 0;
870 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
))
872 if (m_internal
->sock_inputid
<= 0)
874 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_READ
,
875 wx_socket_read
, (gpointer
)this);
880 if (m_internal
->sock_inputid
> 0)
883 gdk_input_remove(m_internal->sock_inputid);
884 m_internal->sock_inputid = 0;
889 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
))
891 if (m_internal
->sock_outputid
<= 0)
893 m_internal
->sock_outputid
= gdk_input_add(m_fd
, GDK_INPUT_WRITE
,
894 wx_socket_write
, (gpointer
)this);
899 if (m_internal
->sock_outputid
> 0)
902 gdk_input_remove(m_internal->sock_outputid);
903 m_internal->sock_outputid = 0;
913 if (m_neededreq
& REQ_READ
)
915 if (m_neededreq
& REQ_WRITE
)
917 if (m_neededreq
& REQ_LOST
)
919 if (m_neededreq
& REQ_ACCEPT
)
921 if (m_neededreq
& REQ_CONNECT
)
924 if (!m_internal
->my_msg
)
925 m_internal
->my_msg
= m_handler
->NewMessage(this);
926 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), m_internal
->my_msg
, mask
);
931 if (m_neededreq
& REQ_READ
)
933 if (m_neededreq
& REQ_WRITE
)
935 if (m_neededreq
& REQ_LOST
)
937 if (m_neededreq
& REQ_ACCEPT
)
939 if (m_neededreq
& REQ_CONNECT
)
942 GUSISetReference( m_fd
,mask
, this ) ;
943 unsigned long flag
= 1;
944 ioctl(m_fd
, FIONBIO
, &flag
);
947 m_processing
= FALSE
;
950 void wxSocketBase::DestroyCallbacks()
952 if (!m_cbkon
|| !m_handler
)
956 m_processing
= FALSE
;
957 #if defined(__WXMOTIF__) || defined(__WXXT__)
958 if (m_internal
->sock_inputid
> 0)
959 XtRemoveInput(m_internal
->sock_inputid
);
960 m_internal
->sock_inputid
= 0;
961 if (m_internal
->sock_outputid
> 0)
962 XtRemoveInput(m_internal
->sock_outputid
);
963 m_internal
->sock_outputid
= 0;
966 if (m_internal
->sock_inputid
> 0)
967 gdk_input_remove(m_internal
->sock_inputid
);
968 m_internal
->sock_inputid
= 0;
969 if (m_internal
->sock_outputid
> 0)
970 gdk_input_remove(m_internal
->sock_outputid
);
971 m_internal
->sock_outputid
= 0;
974 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), 0, 0);
977 GUSISetReference( m_fd
, 0 , 0 ) ;
978 int bottom
= wxMacNetEventsBottom
;
979 while ( wxMacNetEventsTop
!= bottom
)
981 // set all events that reference this socket to nil
982 if ( wxMacNetEventsReferences
[bottom
] == (void*) this )
983 wxMacNetEventsReferences
[bottom
] = NULL
;
985 if ( bottom
== kwxMacNetEventsMax
)
988 SetFlags( m_flags
) ;
992 void wxSocketBase::Notify(bool notify
)
994 if (m_notifyme
== notify
)
1000 m_notifyme
= notify
;
1003 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
1005 wxRequestNotify req_notif
= EventToNotify(req_evt
);
1007 // Mask the current event
1008 SetNotify(m_neededreq
& ~req_notif
);
1010 if (req_evt
<= EVT_WRITE
&& DoRequests(req_evt
))
1013 if (m_waitflags
& 0xF0)
1016 if ((m_waitflags
& 0x0F) == req_evt
)
1026 if (req_evt
== EVT_LOST
)
1028 m_connected
= FALSE
;
1032 OldOnNotify(req_evt
);
1035 SetNotify(m_neededreq
| req_notif
);
1038 wxSocketEvent::wxSocketEvent(int id
)
1041 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
1046 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
1048 wxSocketEvent
event(m_id
);
1050 event
.SetEventObject(this);
1051 event
.m_skevt
= evt
;
1052 ProcessEvent(event
);
1055 m_cbk(*this, evt
, m_cdata
);
1058 // --------------------------------------------------------------
1059 // --------- wxSocketBase functions [Callback, CallbackData] ----
1060 // --------------------------------------------------------------
1062 wxSocketBase::wxSockCbk
wxSocketBase::Callback(wxSocketBase::wxSockCbk _cbk
)
1064 wxSockCbk old_cbk
= m_cbk
;
1070 char *wxSocketBase::CallbackData(char *cdata_
)
1072 char *old_cdata
= m_cdata
;
1078 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
1080 SetNextHandler(&h_evt
);
1084 // --------------------------------------------------------------
1085 // --------- wxSocketBase pushback library ----------------------
1086 // --------------------------------------------------------------
1088 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
1092 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
1093 curr_pos
= m_unread
+ m_unrd_size
;
1095 memcpy(curr_pos
, buffer
, size
);
1096 m_unrd_size
+= size
;
1099 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
1101 char *curr_pos
, *new_buf
;
1103 new_buf
= (char *) malloc(m_unrd_size
+size
);
1104 curr_pos
= new_buf
+ size
;
1106 memcpy(new_buf
, buffer
, size
);
1107 memcpy(curr_pos
, m_unread
, m_unrd_size
);
1111 m_unrd_size
+= size
;
1114 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
1119 if (size
> m_unrd_size
)
1121 memcpy(buffer
, m_unread
, size
);
1124 m_unrd_size
-= size
;
1134 // --------------------------------------------------------------
1135 // --------- wxSocketBase "multi-thread" core -------------------
1136 // --------------------------------------------------------------
1138 bool wxSocketBase::DoRequests(wxRequestEvent req_flag
)
1140 wxNode
*node
= req_list
[req_flag
].First();
1147 SockRequest
*req
= (SockRequest
*)node
->Data();
1155 ret
= recv(m_fd
, req
->buffer
, req
->size
,
1156 (req
->type
== EVT_PEEK
) ? MSG_PEEK
: 0);
1164 if ((len
< req
->size
) && (m_flags
& WAITALL
))
1169 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1170 req_list
[req_flag
].Insert(req
);
1180 ret
= send(m_fd
, req
->buffer
, req
->size
, 0);
1188 if ((len
< req
->size
) && (m_flags
& WAITALL
))
1193 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1194 req_list
[req_flag
].Insert(req
);
1209 void wxSocketBase::WantSpeedBuffer(char *buffer
, size_t nbytes
,
1218 ret
= recv(m_fd
, buffer
, nbytes
,
1219 (evt
== EVT_PEEK
) ? MSG_PEEK
: 0);
1222 ret
= send(m_fd
, buffer
, nbytes
, 0);
1237 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
1242 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
1245 if (m_flags
& SPEED
)
1247 WantSpeedBuffer(buffer
, nbytes
, evt
);
1251 SockRequest
*buf
= new SockRequest
;
1252 wxSockWakeUp
s_wake(NULL
, (int *)&buf_timed_out
, (int)TRUE
);
1255 req_list
[evt
].Append(buf
);
1258 SetNotify(REQ_LOST
| EventToNotify(evt
));
1260 buf
->buffer
= buffer
;
1265 buf
->auto_wakeup
= &s_wake
;
1267 buf_timed_out
= FALSE
;
1269 s_wake
.Start(m_timeout
*1000, TRUE
);
1270 if (m_flags
& NOWAIT
)
1276 while (!buf
->done
&& !buf_timed_out
)
1280 m_lcount
= buf
->nbytes
;
1282 m_error
= ETIMEDOUT
;
1284 m_error
= buf
->error
;
1290 // --------------------------------------------------------------
1292 // --------------------------------------------------------------
1294 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1295 wxSockFlags flags
) :
1296 wxSocketBase(flags
, SOCK_SERVER
)
1298 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1300 if (m_fd
== INVALID_SOCKET
)
1304 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
1306 struct sockaddr
*myaddr
;
1309 addr_man
.Build(myaddr
, len
);
1310 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
1313 if (listen(m_fd
, 5) < 0) {
1314 m_fd
= INVALID_SOCKET
;
1319 // --------------------------------------------------------------
1320 // wxSocketServer Accept
1321 // --------------------------------------------------------------
1323 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
1327 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
1330 struct linger linger
;
1332 linger
.l_linger
= 1;
1334 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1337 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1339 if (!(sock
.m_flags
& SPEED
))
1341 unsigned long flag2
= 1;
1342 ioctl(fd2
, FIONBIO
, &flag2
);
1345 sock
.m_type
= SOCK_INTERNAL
;
1347 sock
.m_connected
= TRUE
;
1352 wxSocketBase
*wxSocketServer::Accept()
1354 wxSocketBase
* sock
= new wxSocketBase();
1356 sock
->SetFlags((wxSockFlags
)m_flags
);
1358 if (!AcceptWith(*sock
))
1362 m_handler
->Register(sock
);
1367 // --------------------------------------------------------------
1368 // wxSocketServer callbacks
1369 // --------------------------------------------------------------
1371 void wxSocketServer::OnRequest(wxRequestEvent evt
)
1373 if (evt
== EVT_ACCEPT
)
1375 OldOnNotify(EVT_ACCEPT
);
1379 // --------------------------------------------------------------
1381 // --------------------------------------------------------------
1383 // --------- wxSocketClient CONSTRUCTOR -------------------------
1384 // --------------------------------------------------------------
1385 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
1386 wxSocketBase(_flags
, SOCK_CLIENT
)
1390 // --------------------------------------------------------------
1391 // --------- wxSocketClient DESTRUCTOR --------------------------
1392 // --------------------------------------------------------------
1393 wxSocketClient::~wxSocketClient()
1397 // --------------------------------------------------------------
1398 // --------- wxSocketClient Connect functions -------------------
1399 // --------------------------------------------------------------
1400 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
1402 struct linger linger
;
1407 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1412 m_connected
= FALSE
;
1415 linger
.l_linger
= 5;
1416 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1418 // Stay in touch with the state of things...
1420 unsigned long flag
= 1;
1421 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1423 // Disable the nagle algorithm, which delays sends till the
1424 // buffer is full (or a certain time period has passed?)...
1426 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1428 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
1431 struct sockaddr
*remote
;
1434 addr_man
.Build(remote
, len
);
1436 if (connect(m_fd
, remote
, len
) != 0)
1439 if (!(m_flags
& SPEED
))
1442 ioctl(m_fd
, FIONBIO
, &flag
);
1451 bool wxSocketClient::WaitOnConnect(long seconds
, long microseconds
)
1453 int ret
= _Wait(seconds
, microseconds
, REQ_CONNECT
| REQ_LOST
);
1461 void wxSocketClient::OnRequest(wxRequestEvent evt
)
1463 if (evt
== EVT_CONNECT
)
1468 SetNotify(m_neededreq
& ~REQ_CONNECT
);
1474 OldOnNotify(EVT_CONNECT
);
1480 wxSocketBase::OnRequest(evt
);
1483 /////////////////////////////////////////////////////////////////
1484 // wxSocketHandler ///////////////////////////////////////////////
1485 /////////////////////////////////////////////////////////////////
1487 wxSocketHandler
*wxSocketHandler::master
= NULL
;
1488 #if defined(__WINDOWS__)
1489 static int win_initialized
= 0;
1492 // --------------------------------------------------------------
1493 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1494 // --------------------------------------------------------------
1497 extern "C" int updatestatus(int s
) ;
1499 void wxMacSocketOnRequestProc( void *refcon
, short event
)
1503 wxSocketBase
*sock
= (wxSocketBase
*) refcon
;
1505 wxSocketBase::wxRequestEvent sk_req
;
1513 sk_req
= wxSocketBase::EVT_READ
;
1514 sock
->OnRequest(sk_req
);
1517 sk_req
= wxSocketBase::EVT_WRITE
;
1518 sock
->OnRequest(sk_req
);
1521 sk_req
= wxSocketBase::EVT_LOST
;
1522 sock
->OnRequest(sk_req
);
1525 sk_req
= wxSocketBase::EVT_ACCEPT
;
1526 sock
->OnRequest(sk_req
);
1529 sk_req
= wxSocketBase::EVT_CONNECT
;
1530 sock
->OnRequest(sk_req
);
1535 updatestatus ( sock
->m_fd
) ;
1539 void wxMacSocketHandlerProc( void *refcon
, short event
)
1541 wxMacNetEventsReferences
[wxMacNetEventsTop
] = refcon
;
1542 wxMacNetEventsEvents
[wxMacNetEventsTop
] = event
;
1544 // clumsy construct in order to never have a incorrect wxMacNetEventsTop (above limits)
1546 if ( wxMacNetEventsTop
+ 1 == kwxMacNetEventsMax
)
1547 wxMacNetEventsTop
= 0 ;
1549 wxMacNetEventsTop
++ ;
1555 extern char wxPanelClassName
[];
1557 LRESULT APIENTRY _EXPORT
wxSocketHandlerWndProc(HWND hWnd
, UINT message
,
1558 WPARAM wParam
, LPARAM lParam
)
1560 if(message
==WM_DESTROY
)
1562 ::SetWindowLong(hWnd
, GWL_WNDPROC
, (LONG
) DefWindowProc
);
1563 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1565 wxSocketHandler
*h_sock
= (wxSocketHandler
*)GetWindowLong(hWnd
, GWL_USERDATA
);
1566 wxNode
*node
= h_sock
->smsg_list
->Find(message
);
1568 wxSocketBase::wxRequestEvent sk_req
;
1569 UINT event
= WSAGETSELECTEVENT(lParam
);
1572 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1574 sock
= (wxSocketBase
*)node
->Data();
1578 sk_req
= wxSocketBase::EVT_READ
;
1581 sk_req
= wxSocketBase::EVT_WRITE
;
1584 sk_req
= wxSocketBase::EVT_LOST
;
1587 sk_req
= wxSocketBase::EVT_ACCEPT
;
1590 sk_req
= wxSocketBase::EVT_CONNECT
;
1593 sock
->OnRequest(sk_req
);
1598 FARPROC wxSocketSubClassProc
= NULL
;
1602 wxSocketHandler::wxSocketHandler()
1604 #if defined(__WINDOWS__)
1605 if (!win_initialized
)
1609 WSAStartup((1 << 8) | 1, &wsaData
);
1610 win_initialized
= 1;
1612 internal
= new wxSockHandlerInternal
;
1613 internal
->sockWin
= ::CreateWindow(wxPanelClassName
, NULL
, 0,
1614 0, 0, 0, 0, NULL
, (HMENU
) NULL
,
1617 // Subclass the window
1618 if (!wxSocketSubClassProc
)
1619 wxSocketSubClassProc
= MakeProcInstance((FARPROC
) wxSocketHandlerWndProc
, wxhInstance
);
1620 ::SetWindowLong(internal
->sockWin
, GWL_WNDPROC
, (LONG
) wxSocketSubClassProc
);
1621 ::SetWindowLong(internal
->sockWin
, GWL_USERDATA
, (LONG
) this);
1623 internal
->firstAvailableMsg
= 5000;
1624 smsg_list
= new wxList(wxKEY_INTEGER
);
1630 signal(SIGPIPE
, SIG_IGN
);
1634 // --------------------------------------------------------------
1635 // --------- wxSocketHandler DESTRUCTOR -------------------------
1636 // --------------------------------------------------------------
1637 wxSocketHandler::~wxSocketHandler()
1639 wxNode
*next_node
, *node
= socks
->First();
1643 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
1646 next_node
= node
->Next();
1656 ::DestroyWindow(internal
->sockWin
);
1658 win_initialized
= 0;
1664 // --------------------------------------------------------------
1665 // --------- wxSocketHandler registering functions --------------
1666 // --------------------------------------------------------------
1668 void wxSocketHandler::Register(wxSocketBase
* sock
)
1672 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next())
1674 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1682 socks
->Append(sock
);
1683 sock
->SetHandler(this);
1684 sock
->SetupCallbacks();
1688 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
1692 for (node
= socks
->First(); node
; node
= node
->Next())
1694 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1699 sock
->DestroyCallbacks();
1700 sock
->SetHandler(NULL
);
1706 unsigned long wxSocketHandler::Count() const
1708 return socks
->Number();
1711 // --------------------------------------------------------------
1712 // --------- wxSocketHandler "big" wait functions ---------------
1713 // --------------------------------------------------------------
1714 void handler_cbk(wxSocketBase
& sock
,
1715 wxSocketBase::wxRequestEvent
WXUNUSED(flags
),
1718 int *a_wait
= (int *)cdata
;
1724 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1728 wxSockWakeUp
s_wake(NULL
, &on_wait
, -2);
1731 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++)
1733 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1737 sock
->SetupCallbacks();
1739 sock
->Callback(handler_cbk
);
1740 sock
->CallbackData((char *)&on_wait
);
1744 s_wake
.Start((seconds
*1000) + (microseconds
/1000), TRUE
);
1749 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++)
1751 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1753 sock
->RestoreState();
1762 void wxSocketHandler::YieldSock()
1766 for (node
= socks
->First(); node
; node
= node
->Next() )
1768 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1772 sock
->SetFlags(wxSocketBase::SPEED
);
1774 sock
->DoRequests(wxSocketBase::EVT_READ
);
1775 sock
->DoRequests(wxSocketBase::EVT_WRITE
);
1777 sock
->RestoreState();
1781 // --------------------------------------------------------------
1782 // --------- wxSocketHandler: create and register the socket ----
1783 // --------------------------------------------------------------
1784 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1785 wxSocketBase::wxSockFlags flags
)
1787 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1793 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1795 wxSocketClient
*client
= new wxSocketClient(flags
);
1802 // --------------------------------------------------------------
1803 // --------- wxSocketHandler: Windows specific methods ----------
1804 // --------------------------------------------------------------
1806 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1808 internal
->firstAvailableMsg
++;
1809 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1810 return internal
->firstAvailableMsg
;
1813 void wxSocketHandler::DestroyMessage(UINT msg
)
1815 wxNode
*node
= smsg_list
->Find(msg
);
1819 HWND
wxSocketHandler::GetHWND() const
1821 return internal
->sockWin
;
1826 bool wxSocketModule::OnInit()
1828 wxSocketHandler::master
= new wxSocketHandler();
1832 void wxSocketModule::OnExit()
1834 delete wxSocketHandler::master
;
1835 wxSocketHandler::master
= NULL
;
1839 void wxMacProcessSocketEvents() ;
1840 void wxMacProcessEvents()
1842 wxMacProcessSocketEvents() ;
1843 (*GUSISpin
)(SP_MISC
, 0) ;
1846 void wxMacProcessSocketEvents()
1848 while ( wxMacNetEventsTop
!= wxMacNetEventsBottom
)
1850 // consume event at wxMacNetEventsBottom
1851 wxMacSocketOnRequestProc(wxMacNetEventsReferences
[wxMacNetEventsBottom
] , wxMacNetEventsEvents
[wxMacNetEventsBottom
] ) ;
1852 wxMacNetEventsBottom
++ ;
1853 if ( wxMacNetEventsBottom
== kwxMacNetEventsMax
)
1854 wxMacNetEventsBottom
= 0 ;