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
);
363 // If we have got the whole needed buffer or if we don't want to
364 // wait then it returns immediately.
365 if (!nbytes
|| (m_lcount
&& !(m_flags
& WAITALL
)) )
368 WantBuffer(buffer
, nbytes
, EVT_READ
);
373 wxSocketBase
& wxSocketBase::Peek(char* buffer
, size_t nbytes
)
375 size_t nbytes_old
= nbytes
;
377 nbytes
-= GetPushback(buffer
, nbytes
, TRUE
);
380 m_lcount
= nbytes_old
;
384 WantBuffer(buffer
, nbytes
, EVT_PEEK
);
389 wxSocketBase
& wxSocketBase::Write(const char *buffer
, size_t nbytes
)
391 WantBuffer((char *)buffer
, nbytes
, EVT_WRITE
);
395 wxSocketBase
& wxSocketBase::ReadMsg(char* buffer
, size_t nbytes
)
398 size_t len
, len2
, sig
;
400 Read((char *)&msg
, sizeof(msg
));
401 if (m_lcount
!= sizeof(msg
))
404 sig
= msg
.sig
[0] & 0xff;
405 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
406 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
407 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
409 if (sig
!= 0xfeeddead)
411 len
= msg
.len
[0] & 0xff;
412 len
|= (size_t)(msg
.len
[1] & 0xff) << 8;
413 len
|= (size_t)(msg
.len
[2] & 0xff) << 16;
414 len
|= (size_t)(msg
.len
[3] & 0xff) << 24;
421 if (Read(buffer
, len
).LastCount() != len
)
423 if (len2
&& (Read(NULL
, len2
).LastCount() != len2
))
425 if (Read((char *)&msg
, sizeof(msg
)).LastCount() != sizeof(msg
))
428 sig
= msg
.sig
[0] & 0xff;
429 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
430 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
431 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
433 if (sig
!= 0xdeadfeed)
439 wxSocketBase
& wxSocketBase::WriteMsg(const char *buffer
, size_t nbytes
)
443 // warning about 'cast truncates constant value'
445 #pragma warning(disable: 4310)
446 #endif // __VISUALC__
448 msg
.sig
[0] = (char) 0xad;
449 msg
.sig
[1] = (char) 0xde;
450 msg
.sig
[2] = (char) 0xed;
451 msg
.sig
[3] = (char) 0xfe;
453 msg
.len
[0] = (char) nbytes
& 0xff;
454 msg
.len
[1] = (char) (nbytes
>> 8) & 0xff;
455 msg
.len
[2] = (char) (nbytes
>> 16) & 0xff;
456 msg
.len
[3] = (char) (nbytes
>> 24) & 0xff;
458 if (Write((char *)&msg
, sizeof(msg
)).LastCount() < sizeof(msg
))
460 if (Write(buffer
, nbytes
).LastCount() < nbytes
)
463 msg
.sig
[0] = (char) 0xed;
464 msg
.sig
[1] = (char) 0xfe;
465 msg
.sig
[2] = (char) 0xad;
466 msg
.sig
[3] = (char) 0xde;
467 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
468 Write((char *)&msg
, sizeof(msg
));
473 #pragma warning(default: 4310)
474 #endif // __VISUALC__
477 wxSocketBase
& wxSocketBase::Unread(const char *buffer
, size_t nbytes
)
479 CreatePushbackAfter(buffer
, nbytes
);
483 bool wxSocketBase::IsData() const
496 FD_SET(m_fd
, &sock_set
);
497 select(FD_SETSIZE
, &sock_set
, NULL
, NULL
, &tv
);
498 return (FD_ISSET(m_fd
, &sock_set
) != 0);
501 // ---------------------------------------------------------------------
502 // --------- wxSocketBase Discard(): deletes all byte in the input queue
503 // ---------------------------------------------------------------------
504 void wxSocketBase::Discard()
506 #define MAX_BUFSIZE (10*1024)
507 char *my_data
= new char[MAX_BUFSIZE
];
508 size_t recv_size
= MAX_BUFSIZE
;
511 SetFlags((wxSockFlags
)(NOWAIT
| SPEED
));
513 while (recv_size
== MAX_BUFSIZE
)
515 recv_size
= Read(my_data
, MAX_BUFSIZE
).LastCount();
524 // If what? Who seems to need unsigned int?
525 // BTW uint isn't even defined on wxMSW for VC++ for some reason. Even if it
526 // were, getpeername/getsockname don't take unsigned int*, they take int*.
528 // Under glibc 2.0.7, socketbits.h declares socklen_t to be unsigned int
529 // and it uses *socklen_t as the 3rd parameter. Robert.
531 // JACS - How can we detect this?
532 // Meanwhile, if your compiler complains about socklen_t,
533 // switch lines below.
536 # define wxSOCKET_INT socklen_t
538 # define wxSOCKET_INT int
541 // --------------------------------------------------------------
542 // wxSocketBase socket info functions
543 // --------------------------------------------------------------
545 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
547 struct sockaddr my_addr
;
548 wxSOCKET_INT len_addr
= sizeof(my_addr
);
553 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0)
556 addr_man
.Disassemble(&my_addr
, len_addr
);
560 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
562 struct sockaddr my_addr
;
563 wxSOCKET_INT len_addr
= sizeof(my_addr
);
568 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0)
572 addr_man
.Disassemble(&my_addr
, len_addr
);
576 // --------------------------------------------------------------
577 // wxSocketBase wait functions
578 // --------------------------------------------------------------
580 void wxSocketBase::SaveState()
582 wxSockState
*state
= new wxSockState
;
584 state
->cbk_on
= m_cbkon
;
585 state
->cbk_set
= m_neededreq
;
587 state
->cdata
= m_cdata
;
588 state
->flags
= m_flags
;
589 state
->notif
= m_notifyme
;
591 m_states
.Append(state
);
594 void wxSocketBase::RestoreState()
598 node
= m_states
.Last();
602 wxSockState
*state
= (wxSockState
*)node
->Data();
604 SetFlags(state
->flags
);
605 m_neededreq
= state
->cbk_set
;
607 m_cdata
= state
->cdata
;
608 m_notifyme
= state
->notif
;
618 // --------------------------------------------------------------
619 // --------- wxSocketBase wait functions ------------------------
620 // --------------------------------------------------------------
622 bool wxSocketBase::_Wait(long seconds
, long microseconds
, int type
)
624 if ((!m_connected
&& !m_connecting
) || m_fd
< 0)
627 wxSockWakeUp
wakeup(this, &m_waitflags
, 0);
630 SetNotify((wxRequestNotify
)type
);
634 wakeup
.Start((int)(seconds
*1000 + (microseconds
/ 1000)), TRUE
);
636 m_waitflags
= 0x80 | type
;
637 while (m_waitflags
& 0x80)
642 if (m_waitflags
& 0x40)
652 bool wxSocketBase::Wait(long seconds
, long microseconds
)
654 return _Wait(seconds
, microseconds
, REQ_ACCEPT
| REQ_CONNECT
|
655 REQ_READ
| REQ_WRITE
| REQ_LOST
);
658 bool wxSocketBase::WaitForRead(long seconds
, long microseconds
)
660 return _Wait(seconds
, microseconds
, REQ_READ
| REQ_LOST
);
663 bool wxSocketBase::WaitForWrite(long seconds
, long microseconds
)
665 return _Wait(seconds
, microseconds
, REQ_WRITE
);
668 bool wxSocketBase::WaitForLost(long seconds
, long microseconds
)
670 return _Wait(seconds
, microseconds
, REQ_LOST
);
673 // --------------------------------------------------------------
674 // --------- wxSocketBase callback management -------------------
675 // --------------------------------------------------------------
677 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
678 #if defined(__WXMOTIF__) || defined(__WXXT__)
679 static void wx_socket_read(XtPointer client
, int *fid
,
680 XtInputId
*WXUNUSED(id
))
683 static void wx_socket_read(gpointer client
, gint fd
,
684 GdkInputCondition
WXUNUSED(cond
))
688 wxSocketBase
*sock
= (wxSocketBase
*)client
;
692 i
= recv(fd
, &c
, 1, MSG_PEEK
);
694 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
))
696 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
702 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
707 sock
->OnRequest(wxSocketBase::EVT_READ
);
711 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
717 sock
->OnRequest(wxSocketBase::EVT_LOST
);
722 #if defined(__WXMOTIF__) || defined(__WXXT__)
723 static void wx_socket_write(XtPointer client
, int *WXUNUSED(fid
),
724 XtInputId
*WXUNUSED(id
))
726 static void wx_socket_write(gpointer client
, gint
WXUNUSED(fd
),
727 GdkInputCondition
WXUNUSED(cond
))
730 wxSocketBase
*sock
= (wxSocketBase
*)client
;
732 if (!sock
->IsConnected())
733 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
735 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
740 Notify_value
wx_sock_read_xview (Notify_client client
, int fd
)
742 wxSocketBase
*sock
= (wxSocketBase
*)client
;
746 i
= recv(fd
, &c
, 1, MSG_PEEK
);
748 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
))
750 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
757 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
758 return (Notify_value
) FALSE
;
760 sock
->OnRequest(wxSocketBase::EVT_READ
);
764 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
767 sock
->OnRequest(wxSocketBase::EVT_LOST
);
770 return (Notify_value
) FALSE
;
773 Notify_value
wx_sock_write_xview (Notify_client client
, int fd
)
775 wxSocketBase
*sock
= (wxSocketBase
*)client
;
777 if (!sock
->IsConnected())
778 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
780 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
782 return (Notify_value
) TRUE
;
786 wxSocketBase::wxRequestNotify
wxSocketBase::EventToNotify(wxRequestEvent evt
)
806 void wxSocketBase::SetFlags(wxSockFlags _flags
)
811 unsigned long flag
= 0;
812 ioctl(m_fd
, FIONBIO
, &flag
);
814 // SPEED and WAITALL are antagonists.
815 m_flags
= (wxSockFlags
)(m_flags
& ~WAITALL
);
821 unsigned long flag
= 1;
822 ioctl(m_fd
, FIONBIO
, &flag
);
826 void wxSocketBase::SetNotify(wxRequestNotify flags
)
828 wxRequestNotify old_needed_req
= m_neededreq
;
829 if (flags
& REQ_ACCEPT
)
831 /* Check if server */
832 if (!(GetClassInfo()->IsKindOf(CLASSINFO(wxSocketServer
))))
833 flags
&= ~REQ_ACCEPT
;
838 if (m_cbkon && old_needed_req != flags) seems to be wrong, Robert Roebling
842 if (old_needed_req
!= flags
)
846 void wxSocketBase::SetupCallbacks()
848 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| (m_flags
& SPEED
))
851 #if defined(__WXMOTIF__) || defined(__WXXT__)
852 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
))
854 if (m_internal
->sock_inputid
<= 0)
856 m_internal
->sock_inputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
857 (XtPointer
*) XtInputReadMask
,
858 (XtInputCallbackProc
) wx_socket_read
,
864 if (m_internal
->sock_inputid
> 0)
866 XtRemoveInput(m_internal
->sock_inputid
);
867 m_internal
->sock_inputid
= 0;
871 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
))
873 if (m_internal
->sock_outputid
<= 0)
875 m_internal
->sock_outputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
876 (XtPointer
*) XtInputWriteMask
,
877 (XtInputCallbackProc
) wx_socket_write
,
883 if (m_internal
->sock_outputid
> 0)
885 XtRemoveInput(m_internal
->sock_outputid
);
886 m_internal
->sock_outputid
= 0;
893 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
))
895 if (m_internal
->sock_inputid
<= 0)
897 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_READ
,
898 wx_socket_read
, (gpointer
)this);
903 if (m_internal
->sock_inputid
> 0)
906 gdk_input_remove(m_internal->sock_inputid);
907 m_internal->sock_inputid = 0;
912 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
))
914 if (m_internal
->sock_outputid
<= 0)
916 m_internal
->sock_outputid
= gdk_input_add(m_fd
, GDK_INPUT_WRITE
,
917 wx_socket_write
, (gpointer
)this);
922 if (m_internal
->sock_outputid
> 0)
925 gdk_input_remove(m_internal->sock_outputid);
926 m_internal->sock_outputid = 0;
936 if (m_neededreq
& REQ_READ
)
938 if (m_neededreq
& REQ_WRITE
)
940 if (m_neededreq
& REQ_LOST
)
942 if (m_neededreq
& REQ_ACCEPT
)
944 if (m_neededreq
& REQ_CONNECT
)
947 if (!m_internal
->my_msg
)
948 m_internal
->my_msg
= m_handler
->NewMessage(this);
949 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), m_internal
->my_msg
, mask
);
954 if (m_neededreq
& REQ_READ
)
956 if (m_neededreq
& REQ_WRITE
)
958 if (m_neededreq
& REQ_LOST
)
960 if (m_neededreq
& REQ_ACCEPT
)
962 if (m_neededreq
& REQ_CONNECT
)
965 GUSISetReference( m_fd
,mask
, this ) ;
966 unsigned long flag
= 1;
967 ioctl(m_fd
, FIONBIO
, &flag
);
970 m_processing
= FALSE
;
973 void wxSocketBase::DestroyCallbacks()
975 if (!m_cbkon
|| !m_handler
)
979 m_processing
= FALSE
;
980 #if defined(__WXMOTIF__) || defined(__WXXT__)
981 if (m_internal
->sock_inputid
> 0)
982 XtRemoveInput(m_internal
->sock_inputid
);
983 m_internal
->sock_inputid
= 0;
984 if (m_internal
->sock_outputid
> 0)
985 XtRemoveInput(m_internal
->sock_outputid
);
986 m_internal
->sock_outputid
= 0;
989 if (m_internal
->sock_inputid
> 0)
990 gdk_input_remove(m_internal
->sock_inputid
);
991 m_internal
->sock_inputid
= 0;
992 if (m_internal
->sock_outputid
> 0)
993 gdk_input_remove(m_internal
->sock_outputid
);
994 m_internal
->sock_outputid
= 0;
997 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), 0, 0);
1000 GUSISetReference( m_fd
, 0 , 0 ) ;
1001 int bottom
= wxMacNetEventsBottom
;
1002 while ( wxMacNetEventsTop
!= bottom
)
1004 // set all events that reference this socket to nil
1005 if ( wxMacNetEventsReferences
[bottom
] == (void*) this )
1006 wxMacNetEventsReferences
[bottom
] = NULL
;
1008 if ( bottom
== kwxMacNetEventsMax
)
1011 SetFlags( m_flags
) ;
1015 void wxSocketBase::Notify(bool notify
)
1017 if (m_notifyme
== notify
)
1023 m_notifyme
= notify
;
1026 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
1028 wxRequestNotify req_notif
= EventToNotify(req_evt
);
1030 // Mask the current event
1031 SetNotify(m_neededreq
& ~req_notif
);
1033 if (req_evt
<= EVT_WRITE
&& DoRequests(req_evt
))
1036 if (m_waitflags
& 0xF0)
1039 if ((m_waitflags
& 0x0F) == req_evt
)
1049 if (req_evt
== EVT_LOST
)
1051 m_connected
= FALSE
;
1055 OldOnNotify(req_evt
);
1058 SetNotify(m_neededreq
| req_notif
);
1061 wxSocketEvent::wxSocketEvent(int id
)
1064 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
1069 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
1071 wxSocketEvent
event(m_id
);
1073 event
.SetEventObject(this);
1074 event
.m_skevt
= evt
;
1075 ProcessEvent(event
);
1078 m_cbk(*this, evt
, m_cdata
);
1081 // --------------------------------------------------------------
1082 // --------- wxSocketBase functions [Callback, CallbackData] ----
1083 // --------------------------------------------------------------
1085 wxSocketBase::wxSockCbk
wxSocketBase::Callback(wxSocketBase::wxSockCbk _cbk
)
1087 wxSockCbk old_cbk
= m_cbk
;
1093 char *wxSocketBase::CallbackData(char *cdata_
)
1095 char *old_cdata
= m_cdata
;
1101 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
1103 SetNextHandler(&h_evt
);
1107 // --------------------------------------------------------------
1108 // --------- wxSocketBase pushback library ----------------------
1109 // --------------------------------------------------------------
1111 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
1115 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
1116 curr_pos
= m_unread
+ m_unrd_size
;
1118 memcpy(curr_pos
, buffer
, size
);
1119 m_unrd_size
+= size
;
1122 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
1124 char *curr_pos
, *new_buf
;
1126 new_buf
= (char *) malloc(m_unrd_size
+size
);
1127 curr_pos
= new_buf
+ size
;
1129 memcpy(new_buf
, buffer
, size
);
1130 memcpy(curr_pos
, m_unread
, m_unrd_size
);
1134 m_unrd_size
+= size
;
1137 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
1142 if (size
> m_unrd_size
)
1144 memcpy(buffer
, m_unread
, size
);
1147 m_unrd_size
-= size
;
1157 // --------------------------------------------------------------
1158 // --------- wxSocketBase "multi-thread" core -------------------
1159 // --------------------------------------------------------------
1161 bool wxSocketBase::DoRequests(wxRequestEvent req_flag
)
1163 wxNode
*node
= req_list
[req_flag
].First();
1170 SockRequest
*req
= (SockRequest
*)node
->Data();
1178 ret
= recv(m_fd
, req
->buffer
, req
->size
,
1179 (req
->type
== EVT_PEEK
) ? MSG_PEEK
: 0);
1187 if ((len
< req
->size
) && (m_flags
& WAITALL
))
1192 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1193 req_list
[req_flag
].Insert(req
);
1203 ret
= send(m_fd
, req
->buffer
, req
->size
, 0);
1211 if ((len
< req
->size
) && (m_flags
& WAITALL
))
1216 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1217 req_list
[req_flag
].Insert(req
);
1232 void wxSocketBase::WantSpeedBuffer(char *buffer
, size_t nbytes
,
1241 ret
= recv(m_fd
, buffer
, nbytes
,
1242 (evt
== EVT_PEEK
) ? MSG_PEEK
: 0);
1245 ret
= send(m_fd
, buffer
, nbytes
, 0);
1260 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
1265 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
1268 if (m_flags
& SPEED
)
1270 WantSpeedBuffer(buffer
, nbytes
, evt
);
1274 SockRequest
*buf
= new SockRequest
;
1275 wxSockWakeUp
s_wake(NULL
, (int *)&buf_timed_out
, (int)TRUE
);
1278 req_list
[evt
].Append(buf
);
1281 SetNotify(REQ_LOST
| EventToNotify(evt
));
1283 buf
->buffer
= buffer
;
1288 buf
->auto_wakeup
= &s_wake
;
1290 buf_timed_out
= FALSE
;
1292 s_wake
.Start(m_timeout
*1000, TRUE
);
1293 if (m_flags
& NOWAIT
)
1299 while (!buf
->done
&& !buf_timed_out
)
1303 m_lcount
= buf
->nbytes
;
1305 m_error
= ETIMEDOUT
;
1307 m_error
= buf
->error
;
1313 // --------------------------------------------------------------
1315 // --------------------------------------------------------------
1317 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1318 wxSockFlags flags
) :
1319 wxSocketBase(flags
, SOCK_SERVER
)
1321 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1323 if (m_fd
== INVALID_SOCKET
)
1327 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
1329 struct sockaddr
*myaddr
;
1332 addr_man
.Build(myaddr
, len
);
1333 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
1336 if (listen(m_fd
, 5) < 0) {
1337 m_fd
= INVALID_SOCKET
;
1342 // --------------------------------------------------------------
1343 // wxSocketServer Accept
1344 // --------------------------------------------------------------
1346 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
1350 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
1353 struct linger linger
;
1355 linger
.l_linger
= 1;
1357 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1360 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1362 if (!(sock
.m_flags
& SPEED
))
1364 unsigned long flag2
= 1;
1365 ioctl(fd2
, FIONBIO
, &flag2
);
1368 sock
.m_type
= SOCK_INTERNAL
;
1370 sock
.m_connected
= TRUE
;
1375 wxSocketBase
*wxSocketServer::Accept()
1377 wxSocketBase
* sock
= new wxSocketBase();
1379 sock
->SetFlags((wxSockFlags
)m_flags
);
1381 if (!AcceptWith(*sock
))
1385 m_handler
->Register(sock
);
1390 // --------------------------------------------------------------
1391 // wxSocketServer callbacks
1392 // --------------------------------------------------------------
1394 void wxSocketServer::OnRequest(wxRequestEvent evt
)
1396 if (evt
== EVT_ACCEPT
)
1398 OldOnNotify(EVT_ACCEPT
);
1402 // --------------------------------------------------------------
1404 // --------------------------------------------------------------
1406 // --------- wxSocketClient CONSTRUCTOR -------------------------
1407 // --------------------------------------------------------------
1408 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
1409 wxSocketBase(_flags
, SOCK_CLIENT
)
1413 // --------------------------------------------------------------
1414 // --------- wxSocketClient DESTRUCTOR --------------------------
1415 // --------------------------------------------------------------
1416 wxSocketClient::~wxSocketClient()
1420 // --------------------------------------------------------------
1421 // --------- wxSocketClient Connect functions -------------------
1422 // --------------------------------------------------------------
1423 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
1425 struct linger linger
;
1430 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1435 m_connected
= FALSE
;
1438 linger
.l_linger
= 5;
1439 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1441 // Stay in touch with the state of things...
1443 unsigned long flag
= 1;
1444 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1446 // Disable the nagle algorithm, which delays sends till the
1447 // buffer is full (or a certain time period has passed?)...
1449 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1451 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
1454 struct sockaddr
*remote
;
1457 addr_man
.Build(remote
, len
);
1459 if (connect(m_fd
, remote
, len
) != 0)
1462 if (!(m_flags
& SPEED
))
1465 ioctl(m_fd
, FIONBIO
, &flag
);
1474 bool wxSocketClient::WaitOnConnect(long seconds
, long microseconds
)
1476 int ret
= _Wait(seconds
, microseconds
, REQ_CONNECT
| REQ_LOST
);
1484 void wxSocketClient::OnRequest(wxRequestEvent evt
)
1486 if (evt
== EVT_CONNECT
)
1491 SetNotify(m_neededreq
& ~REQ_CONNECT
);
1497 OldOnNotify(EVT_CONNECT
);
1503 wxSocketBase::OnRequest(evt
);
1506 /////////////////////////////////////////////////////////////////
1507 // wxSocketHandler ///////////////////////////////////////////////
1508 /////////////////////////////////////////////////////////////////
1510 wxSocketHandler
*wxSocketHandler::master
= NULL
;
1511 #if defined(__WINDOWS__)
1512 static int win_initialized
= 0;
1515 // --------------------------------------------------------------
1516 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1517 // --------------------------------------------------------------
1520 extern "C" int updatestatus(int s
) ;
1522 void wxMacSocketOnRequestProc( void *refcon
, short event
)
1526 wxSocketBase
*sock
= (wxSocketBase
*) refcon
;
1528 wxSocketBase::wxRequestEvent sk_req
;
1536 sk_req
= wxSocketBase::EVT_READ
;
1537 sock
->OnRequest(sk_req
);
1540 sk_req
= wxSocketBase::EVT_WRITE
;
1541 sock
->OnRequest(sk_req
);
1544 sk_req
= wxSocketBase::EVT_LOST
;
1545 sock
->OnRequest(sk_req
);
1548 sk_req
= wxSocketBase::EVT_ACCEPT
;
1549 sock
->OnRequest(sk_req
);
1552 sk_req
= wxSocketBase::EVT_CONNECT
;
1553 sock
->OnRequest(sk_req
);
1558 updatestatus ( sock
->m_fd
) ;
1562 void wxMacSocketHandlerProc( void *refcon
, short event
)
1564 wxMacNetEventsReferences
[wxMacNetEventsTop
] = refcon
;
1565 wxMacNetEventsEvents
[wxMacNetEventsTop
] = event
;
1567 // clumsy construct in order to never have a incorrect wxMacNetEventsTop (above limits)
1569 if ( wxMacNetEventsTop
+ 1 == kwxMacNetEventsMax
)
1570 wxMacNetEventsTop
= 0 ;
1572 wxMacNetEventsTop
++ ;
1578 extern char wxPanelClassName
[];
1580 LRESULT APIENTRY _EXPORT
wxSocketHandlerWndProc(HWND hWnd
, UINT message
,
1581 WPARAM wParam
, LPARAM lParam
)
1583 if(message
==WM_DESTROY
)
1585 ::SetWindowLong(hWnd
, GWL_WNDPROC
, (LONG
) DefWindowProc
);
1586 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1588 wxSocketHandler
*h_sock
= (wxSocketHandler
*)GetWindowLong(hWnd
, GWL_USERDATA
);
1589 wxNode
*node
= h_sock
->smsg_list
->Find(message
);
1591 wxSocketBase::wxRequestEvent sk_req
;
1592 UINT event
= WSAGETSELECTEVENT(lParam
);
1595 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1597 sock
= (wxSocketBase
*)node
->Data();
1601 sk_req
= wxSocketBase::EVT_READ
;
1604 sk_req
= wxSocketBase::EVT_WRITE
;
1607 sk_req
= wxSocketBase::EVT_LOST
;
1610 sk_req
= wxSocketBase::EVT_ACCEPT
;
1613 sk_req
= wxSocketBase::EVT_CONNECT
;
1617 wxFAIL_MSG("invalid socket event");
1621 sock
->OnRequest(sk_req
);
1626 FARPROC wxSocketSubClassProc
= NULL
;
1630 wxSocketHandler::wxSocketHandler()
1632 #if defined(__WINDOWS__)
1633 if (!win_initialized
)
1637 WSAStartup((1 << 8) | 1, &wsaData
);
1638 win_initialized
= 1;
1640 internal
= new wxSockHandlerInternal
;
1641 internal
->sockWin
= ::CreateWindow(wxPanelClassName
, NULL
, 0,
1642 0, 0, 0, 0, NULL
, (HMENU
) NULL
,
1645 // Subclass the window
1646 if (!wxSocketSubClassProc
)
1647 wxSocketSubClassProc
= MakeProcInstance((FARPROC
) wxSocketHandlerWndProc
, wxhInstance
);
1648 ::SetWindowLong(internal
->sockWin
, GWL_WNDPROC
, (LONG
) wxSocketSubClassProc
);
1649 ::SetWindowLong(internal
->sockWin
, GWL_USERDATA
, (LONG
) this);
1651 internal
->firstAvailableMsg
= 5000;
1652 smsg_list
= new wxList(wxKEY_INTEGER
);
1658 signal(SIGPIPE
, SIG_IGN
);
1662 // --------------------------------------------------------------
1663 // --------- wxSocketHandler DESTRUCTOR -------------------------
1664 // --------------------------------------------------------------
1665 wxSocketHandler::~wxSocketHandler()
1667 wxNode
*next_node
, *node
= socks
->First();
1671 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
1674 next_node
= node
->Next();
1684 ::DestroyWindow(internal
->sockWin
);
1686 win_initialized
= 0;
1692 // --------------------------------------------------------------
1693 // --------- wxSocketHandler registering functions --------------
1694 // --------------------------------------------------------------
1696 void wxSocketHandler::Register(wxSocketBase
* sock
)
1700 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next())
1702 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1710 socks
->Append(sock
);
1711 sock
->SetHandler(this);
1712 sock
->SetupCallbacks();
1716 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
1720 for (node
= socks
->First(); node
; node
= node
->Next())
1722 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1727 sock
->DestroyCallbacks();
1728 sock
->SetHandler(NULL
);
1734 unsigned long wxSocketHandler::Count() const
1736 return socks
->Number();
1739 // --------------------------------------------------------------
1740 // --------- wxSocketHandler "big" wait functions ---------------
1741 // --------------------------------------------------------------
1742 void handler_cbk(wxSocketBase
& sock
,
1743 wxSocketBase::wxRequestEvent
WXUNUSED(flags
),
1746 int *a_wait
= (int *)cdata
;
1752 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1756 wxSockWakeUp
s_wake(NULL
, &on_wait
, -2);
1759 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++)
1761 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1765 sock
->SetupCallbacks();
1767 sock
->Callback(handler_cbk
);
1768 sock
->CallbackData((char *)&on_wait
);
1772 s_wake
.Start((seconds
*1000) + (microseconds
/1000), TRUE
);
1777 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++)
1779 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1781 sock
->RestoreState();
1790 void wxSocketHandler::YieldSock()
1794 for (node
= socks
->First(); node
; node
= node
->Next() )
1796 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1800 sock
->SetFlags(wxSocketBase::SPEED
);
1802 sock
->DoRequests(wxSocketBase::EVT_READ
);
1803 sock
->DoRequests(wxSocketBase::EVT_WRITE
);
1805 sock
->RestoreState();
1809 // --------------------------------------------------------------
1810 // --------- wxSocketHandler: create and register the socket ----
1811 // --------------------------------------------------------------
1812 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1813 wxSocketBase::wxSockFlags flags
)
1815 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1821 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1823 wxSocketClient
*client
= new wxSocketClient(flags
);
1830 // --------------------------------------------------------------
1831 // --------- wxSocketHandler: Windows specific methods ----------
1832 // --------------------------------------------------------------
1834 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1836 internal
->firstAvailableMsg
++;
1837 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1838 return internal
->firstAvailableMsg
;
1841 void wxSocketHandler::DestroyMessage(UINT msg
)
1843 wxNode
*node
= smsg_list
->Find(msg
);
1847 HWND
wxSocketHandler::GetHWND() const
1849 return internal
->sockWin
;
1854 bool wxSocketModule::OnInit()
1856 wxSocketHandler::master
= new wxSocketHandler();
1860 void wxSocketModule::OnExit()
1862 delete wxSocketHandler::master
;
1863 wxSocketHandler::master
= NULL
;
1867 void wxMacProcessSocketEvents() ;
1868 void wxMacProcessEvents()
1870 wxMacProcessSocketEvents() ;
1871 (*GUSISpin
)(SP_MISC
, 0) ;
1874 void wxMacProcessSocketEvents()
1876 while ( wxMacNetEventsTop
!= wxMacNetEventsBottom
)
1878 // consume event at wxMacNetEventsBottom
1879 wxMacSocketOnRequestProc(wxMacNetEventsReferences
[wxMacNetEventsBottom
] , wxMacNetEventsEvents
[wxMacNetEventsBottom
] ) ;
1880 wxMacNetEventsBottom
++ ;
1881 if ( wxMacNetEventsBottom
== kwxMacNetEventsMax
)
1882 wxMacNetEventsBottom
= 0 ;