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"
17 typedef int socklen_t
;
20 // For compilers that support precompilation, includes "wx.h".
21 #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
)
362 count
= GetPushback(buffer
, nbytes
, FALSE
);
366 // If we have got the whole needed buffer or if we don't want to
367 // wait then it returns immediately.
368 if (!nbytes
|| (count
&& !(m_flags
& WAITALL
)) ) {
374 WantBuffer(buffer
, nbytes
, EVT_READ
);
380 wxSocketBase
& wxSocketBase::Peek(char* buffer
, size_t nbytes
)
384 count
= GetPushback(buffer
, nbytes
, TRUE
);
385 if (nbytes
-count
== 0)
394 WantBuffer(buffer
, nbytes
, EVT_PEEK
);
400 wxSocketBase
& wxSocketBase::Write(const char *buffer
, size_t nbytes
)
402 WantBuffer((char *)buffer
, nbytes
, EVT_WRITE
);
406 wxSocketBase
& wxSocketBase::ReadMsg(char* buffer
, size_t nbytes
)
409 size_t len
, len2
, sig
;
411 Read((char *)&msg
, sizeof(msg
));
412 if (m_lcount
!= sizeof(msg
))
415 sig
= msg
.sig
[0] & 0xff;
416 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
417 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
418 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
420 if (sig
!= 0xfeeddead)
422 len
= msg
.len
[0] & 0xff;
423 len
|= (size_t)(msg
.len
[1] & 0xff) << 8;
424 len
|= (size_t)(msg
.len
[2] & 0xff) << 16;
425 len
|= (size_t)(msg
.len
[3] & 0xff) << 24;
432 if (Read(buffer
, len
).LastCount() != len
)
434 if (len2
&& (Read(NULL
, len2
).LastCount() != len2
))
436 if (Read((char *)&msg
, sizeof(msg
)).LastCount() != sizeof(msg
))
439 sig
= msg
.sig
[0] & 0xff;
440 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
441 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
442 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
444 if (sig
!= 0xdeadfeed)
450 wxSocketBase
& wxSocketBase::WriteMsg(const char *buffer
, size_t nbytes
)
454 // warning about 'cast truncates constant value'
456 #pragma warning(disable: 4310)
457 #endif // __VISUALC__
459 msg
.sig
[0] = (char) 0xad;
460 msg
.sig
[1] = (char) 0xde;
461 msg
.sig
[2] = (char) 0xed;
462 msg
.sig
[3] = (char) 0xfe;
464 msg
.len
[0] = (char) nbytes
& 0xff;
465 msg
.len
[1] = (char) (nbytes
>> 8) & 0xff;
466 msg
.len
[2] = (char) (nbytes
>> 16) & 0xff;
467 msg
.len
[3] = (char) (nbytes
>> 24) & 0xff;
469 if (Write((char *)&msg
, sizeof(msg
)).LastCount() < sizeof(msg
))
471 if (Write(buffer
, nbytes
).LastCount() < nbytes
)
474 msg
.sig
[0] = (char) 0xed;
475 msg
.sig
[1] = (char) 0xfe;
476 msg
.sig
[2] = (char) 0xad;
477 msg
.sig
[3] = (char) 0xde;
478 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
479 Write((char *)&msg
, sizeof(msg
));
484 #pragma warning(default: 4310)
485 #endif // __VISUALC__
488 wxSocketBase
& wxSocketBase::Unread(const char *buffer
, size_t nbytes
)
490 CreatePushbackAfter(buffer
, nbytes
);
494 bool wxSocketBase::IsData() const
507 FD_SET(m_fd
, &sock_set
);
508 select(FD_SETSIZE
, &sock_set
, NULL
, NULL
, &tv
);
509 return (FD_ISSET(m_fd
, &sock_set
) != 0);
512 // ---------------------------------------------------------------------
513 // --------- wxSocketBase Discard(): deletes all byte in the input queue
514 // ---------------------------------------------------------------------
515 void wxSocketBase::Discard()
517 #define MAX_BUFSIZE (10*1024)
518 char *my_data
= new char[MAX_BUFSIZE
];
519 size_t recv_size
= MAX_BUFSIZE
;
522 SetFlags((wxSockFlags
)(NOWAIT
| SPEED
));
524 while (recv_size
== MAX_BUFSIZE
)
526 recv_size
= Read(my_data
, MAX_BUFSIZE
).LastCount();
535 // If what? Who seems to need unsigned int?
536 // BTW uint isn't even defined on wxMSW for VC++ for some reason. Even if it
537 // were, getpeername/getsockname don't take unsigned int*, they take int*.
539 // Under glibc 2.0.7, socketbits.h declares socklen_t to be unsigned int
540 // and it uses *socklen_t as the 3rd parameter. Robert.
542 // JACS - How can we detect this?
543 // Meanwhile, if your compiler complains about socklen_t,
544 // switch lines below.
547 # typedef socklen_t wxSOCKET_INT;
548 #elif defined(__AIX__)
549 # typedef size_t wxSOCKET_INT;
551 # typedef int wxSOCKET_INT;
554 // --------------------------------------------------------------
555 // wxSocketBase socket info functions
556 // --------------------------------------------------------------
558 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
560 struct sockaddr my_addr
;
561 wxSOCKET_INT len_addr
= sizeof(my_addr
);
566 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0)
569 addr_man
.Disassemble(&my_addr
, len_addr
);
573 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
575 struct sockaddr my_addr
;
576 wxSOCKET_INT len_addr
= sizeof(my_addr
);
581 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0)
585 addr_man
.Disassemble(&my_addr
, len_addr
);
589 // --------------------------------------------------------------
590 // wxSocketBase wait functions
591 // --------------------------------------------------------------
593 void wxSocketBase::SaveState()
595 wxSockState
*state
= new wxSockState
;
597 state
->cbk_on
= m_cbkon
;
598 state
->cbk_set
= m_neededreq
;
600 state
->cdata
= m_cdata
;
601 state
->flags
= m_flags
;
602 state
->notif
= m_notifyme
;
604 m_states
.Append(state
);
607 void wxSocketBase::RestoreState()
611 node
= m_states
.Last();
615 wxSockState
*state
= (wxSockState
*)node
->Data();
617 SetFlags(state
->flags
);
618 m_neededreq
= state
->cbk_set
;
620 m_cdata
= state
->cdata
;
621 m_notifyme
= state
->notif
;
631 // --------------------------------------------------------------
632 // --------- wxSocketBase wait functions ------------------------
633 // --------------------------------------------------------------
635 bool wxSocketBase::_Wait(long seconds
, long microseconds
, int type
)
637 if ((!m_connected
&& !m_connecting
) || m_fd
< 0)
640 wxSockWakeUp
wakeup(this, &m_waitflags
, 0);
643 SetNotify((wxRequestNotify
)type
);
647 wakeup
.Start((int)(seconds
*1000 + (microseconds
/ 1000)), TRUE
);
649 m_waitflags
= 0x80 | type
;
650 while (m_waitflags
& 0x80)
655 if (m_waitflags
& 0x40)
665 bool wxSocketBase::Wait(long seconds
, long microseconds
)
667 return _Wait(seconds
, microseconds
, REQ_ACCEPT
| REQ_CONNECT
|
668 REQ_READ
| REQ_WRITE
| REQ_LOST
);
671 bool wxSocketBase::WaitForRead(long seconds
, long microseconds
)
673 return _Wait(seconds
, microseconds
, REQ_READ
| REQ_LOST
);
676 bool wxSocketBase::WaitForWrite(long seconds
, long microseconds
)
678 return _Wait(seconds
, microseconds
, REQ_WRITE
);
681 bool wxSocketBase::WaitForLost(long seconds
, long microseconds
)
683 return _Wait(seconds
, microseconds
, REQ_LOST
);
686 // --------------------------------------------------------------
687 // --------- wxSocketBase callback management -------------------
688 // --------------------------------------------------------------
691 void wxPrereadSocket(wxSocketBase
*sock
)
697 got
= recv(sock
->m_fd
, tmp_buf
, 1024, 0);
699 sock
->CreatePushbackAfter(tmp_buf
, got
);
704 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
705 #if defined(__WXMOTIF__) || defined(__WXXT__)
706 static void wx_socket_read(XtPointer client
, int *fid
,
707 XtInputId
*WXUNUSED(id
))
710 static void wx_socket_read(gpointer client
, gint fd
,
711 GdkInputCondition
WXUNUSED(cond
))
715 wxSocketBase
*sock
= (wxSocketBase
*)client
;
719 i
= recv(fd
, &c
, 1, MSG_PEEK
);
721 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
))
723 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
729 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
732 // We can't exit from the GDK main loop because it doesn't accept
733 // destroying input event while we are in a event dispatch.
734 // So we will preread socket and we put the data in the pushback.
735 wxPrereadSocket(sock
);
736 // Then we set the socket as BLOCKING
738 ioctl(fd
, FIONBIO
, &flag
);
743 sock
->OnRequest(wxSocketBase::EVT_READ
);
747 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
753 sock
->OnRequest(wxSocketBase::EVT_LOST
);
758 #if defined(__WXMOTIF__) || defined(__WXXT__)
759 static void wx_socket_write(XtPointer client
, int *WXUNUSED(fid
),
760 XtInputId
*WXUNUSED(id
))
762 static void wx_socket_write(gpointer client
, gint
WXUNUSED(fd
),
763 GdkInputCondition
WXUNUSED(cond
))
766 wxSocketBase
*sock
= (wxSocketBase
*)client
;
768 if (!sock
->IsConnected())
769 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
771 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
776 Notify_value
wx_sock_read_xview (Notify_client client
, int fd
)
778 wxSocketBase
*sock
= (wxSocketBase
*)client
;
782 i
= recv(fd
, &c
, 1, MSG_PEEK
);
784 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
))
786 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
793 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
794 return (Notify_value
) FALSE
;
796 sock
->OnRequest(wxSocketBase::EVT_READ
);
800 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
803 sock
->OnRequest(wxSocketBase::EVT_LOST
);
806 return (Notify_value
) FALSE
;
809 Notify_value
wx_sock_write_xview (Notify_client client
, int fd
)
811 wxSocketBase
*sock
= (wxSocketBase
*)client
;
813 if (!sock
->IsConnected())
814 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
816 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
818 return (Notify_value
) TRUE
;
822 wxSocketBase::wxRequestNotify
wxSocketBase::EventToNotify(wxRequestEvent evt
)
842 void wxSocketBase::SetFlags(wxSockFlags _flags
)
847 unsigned long flag
= 0;
848 ioctl(m_fd
, FIONBIO
, &flag
);
850 // SPEED and WAITALL are antagonists.
851 m_flags
= (wxSockFlags
)(m_flags
& ~WAITALL
);
857 unsigned long flag
= 1;
858 ioctl(m_fd
, FIONBIO
, &flag
);
862 void wxSocketBase::SetNotify(wxRequestNotify flags
)
864 wxRequestNotify old_needed_req
= m_neededreq
;
865 if (flags
& REQ_ACCEPT
)
867 /* Check if server */
868 if (!(GetClassInfo()->IsKindOf(CLASSINFO(wxSocketServer
))))
869 flags
&= ~REQ_ACCEPT
;
874 if (m_cbkon && old_needed_req != flags) seems to be wrong, Robert Roebling
878 if (old_needed_req
!= flags
)
882 void wxSocketBase::SetupCallbacks()
884 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| (m_flags
& SPEED
))
887 #if defined(__WXMOTIF__) || defined(__WXXT__)
888 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
))
890 if (m_internal
->sock_inputid
<= 0)
892 m_internal
->sock_inputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
893 (XtPointer
*) XtInputReadMask
,
894 (XtInputCallbackProc
) wx_socket_read
,
900 if (m_internal
->sock_inputid
> 0)
902 XtRemoveInput(m_internal
->sock_inputid
);
903 m_internal
->sock_inputid
= 0;
907 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
))
909 if (m_internal
->sock_outputid
<= 0)
911 m_internal
->sock_outputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
912 (XtPointer
*) XtInputWriteMask
,
913 (XtInputCallbackProc
) wx_socket_write
,
919 if (m_internal
->sock_outputid
> 0)
921 XtRemoveInput(m_internal
->sock_outputid
);
922 m_internal
->sock_outputid
= 0;
929 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
))
931 if (m_internal
->sock_inputid
<= 0)
933 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_READ
,
934 wx_socket_read
, (gpointer
)this);
939 if (m_internal
->sock_inputid
> 0)
942 gdk_input_remove(m_internal->sock_inputid);
943 m_internal->sock_inputid = 0;
948 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
))
950 if (m_internal
->sock_outputid
<= 0)
952 m_internal
->sock_outputid
= gdk_input_add(m_fd
, GDK_INPUT_WRITE
,
953 wx_socket_write
, (gpointer
)this);
958 if (m_internal
->sock_outputid
> 0)
961 gdk_input_remove(m_internal->sock_outputid);
962 m_internal->sock_outputid = 0;
972 if (m_neededreq
& REQ_READ
)
974 if (m_neededreq
& REQ_WRITE
)
976 if (m_neededreq
& REQ_LOST
)
978 if (m_neededreq
& REQ_ACCEPT
)
980 if (m_neededreq
& REQ_CONNECT
)
983 if (!m_internal
->my_msg
)
984 m_internal
->my_msg
= m_handler
->NewMessage(this);
985 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), m_internal
->my_msg
, mask
);
990 if (m_neededreq
& REQ_READ
)
992 if (m_neededreq
& REQ_WRITE
)
994 if (m_neededreq
& REQ_LOST
)
996 if (m_neededreq
& REQ_ACCEPT
)
998 if (m_neededreq
& REQ_CONNECT
)
1001 GUSISetReference( m_fd
,mask
, this ) ;
1002 unsigned long flag
= 1;
1003 ioctl(m_fd
, FIONBIO
, &flag
);
1006 m_processing
= FALSE
;
1009 void wxSocketBase::DestroyCallbacks()
1011 if (!m_cbkon
|| !m_handler
)
1015 m_processing
= FALSE
;
1016 #if defined(__WXMOTIF__) || defined(__WXXT__)
1017 if (m_internal
->sock_inputid
> 0)
1018 XtRemoveInput(m_internal
->sock_inputid
);
1019 m_internal
->sock_inputid
= 0;
1020 if (m_internal
->sock_outputid
> 0)
1021 XtRemoveInput(m_internal
->sock_outputid
);
1022 m_internal
->sock_outputid
= 0;
1025 if (m_internal
->sock_inputid
> 0)
1026 gdk_input_remove(m_internal
->sock_inputid
);
1027 m_internal
->sock_inputid
= 0;
1028 if (m_internal
->sock_outputid
> 0)
1029 gdk_input_remove(m_internal
->sock_outputid
);
1030 m_internal
->sock_outputid
= 0;
1033 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), 0, 0);
1036 GUSISetReference( m_fd
, 0 , 0 ) ;
1037 int bottom
= wxMacNetEventsBottom
;
1038 while ( wxMacNetEventsTop
!= bottom
)
1040 // set all events that reference this socket to nil
1041 if ( wxMacNetEventsReferences
[bottom
] == (void*) this )
1042 wxMacNetEventsReferences
[bottom
] = NULL
;
1044 if ( bottom
== kwxMacNetEventsMax
)
1047 SetFlags( m_flags
) ;
1051 void wxSocketBase::Notify(bool notify
)
1053 if (m_notifyme
== notify
)
1059 m_notifyme
= notify
;
1062 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
1064 wxRequestNotify req_notif
= EventToNotify(req_evt
);
1066 // Mask the current event
1067 SetNotify(m_neededreq
& ~req_notif
);
1069 if (req_evt
<= EVT_WRITE
&& DoRequests(req_evt
))
1072 if (m_waitflags
& 0xF0)
1075 if ((m_waitflags
& 0x0F) == req_evt
)
1085 if (req_evt
== EVT_LOST
)
1087 m_connected
= FALSE
;
1091 OldOnNotify(req_evt
);
1094 SetNotify(m_neededreq
| req_notif
);
1097 wxSocketEvent::wxSocketEvent(int id
)
1100 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
1105 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
1107 wxSocketEvent
event(m_id
);
1109 event
.SetEventObject(this);
1110 event
.m_skevt
= evt
;
1111 ProcessEvent(event
);
1114 m_cbk(*this, evt
, m_cdata
);
1117 // --------------------------------------------------------------
1118 // --------- wxSocketBase functions [Callback, CallbackData] ----
1119 // --------------------------------------------------------------
1121 wxSocketBase::wxSockCbk
wxSocketBase::Callback(wxSocketBase::wxSockCbk _cbk
)
1123 wxSockCbk old_cbk
= m_cbk
;
1129 char *wxSocketBase::CallbackData(char *cdata_
)
1131 char *old_cdata
= m_cdata
;
1137 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
1139 SetNextHandler(&h_evt
);
1143 // --------------------------------------------------------------
1144 // --------- wxSocketBase pushback library ----------------------
1145 // --------------------------------------------------------------
1147 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
1151 if (m_unread
!= NULL
)
1152 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
1154 m_unread
= (char *) malloc(size
);
1155 curr_pos
= m_unread
+ m_unrd_size
;
1157 memcpy(curr_pos
, buffer
, size
);
1158 m_unrd_size
+= size
;
1161 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
1163 char *curr_pos
, *new_buf
;
1165 new_buf
= (char *) malloc(m_unrd_size
+size
);
1166 curr_pos
= new_buf
+ size
;
1168 memcpy(new_buf
, buffer
, size
);
1169 if (m_unrd_size
!= 0) {
1170 memcpy(curr_pos
, m_unread
, m_unrd_size
);
1174 m_unrd_size
+= size
;
1177 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
1182 if (size
> m_unrd_size
)
1184 memcpy(buffer
, m_unread
, size
);
1187 m_unrd_size
-= size
;
1188 if (m_unrd_size
== 0) {
1197 // --------------------------------------------------------------
1198 // --------- wxSocketBase "multi-thread" core -------------------
1199 // --------------------------------------------------------------
1201 bool wxSocketBase::DoRequests(wxRequestEvent req_flag
)
1203 wxNode
*node
= req_list
[req_flag
].First();
1210 SockRequest
*req
= (SockRequest
*)node
->Data();
1218 ret
= recv(m_fd
, req
->buffer
, req
->size
,
1219 (req
->type
== EVT_PEEK
) ? MSG_PEEK
: 0);
1227 if ((len
< req
->size
) && (m_flags
& WAITALL
))
1232 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1233 req_list
[req_flag
].Insert(req
);
1243 ret
= send(m_fd
, req
->buffer
, req
->size
, 0);
1251 if ((len
< req
->size
) && (m_flags
& WAITALL
))
1256 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1257 req_list
[req_flag
].Insert(req
);
1272 void wxSocketBase::WantSpeedBuffer(char *buffer
, size_t nbytes
,
1281 ret
= recv(m_fd
, buffer
, nbytes
,
1282 (evt
== EVT_PEEK
) ? MSG_PEEK
: 0);
1285 ret
= send(m_fd
, buffer
, nbytes
, 0);
1300 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
1305 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
1308 if (m_flags
& SPEED
)
1310 WantSpeedBuffer(buffer
, nbytes
, evt
);
1314 SockRequest
*buf
= new SockRequest
;
1315 wxSockWakeUp
s_wake(NULL
, (int *)&buf_timed_out
, (int)TRUE
);
1318 req_list
[evt
].Append(buf
);
1321 SetNotify(REQ_LOST
| EventToNotify(evt
));
1323 buf
->buffer
= buffer
;
1328 buf
->auto_wakeup
= &s_wake
;
1330 buf_timed_out
= FALSE
;
1332 s_wake
.Start(m_timeout
*1000, TRUE
);
1333 if (m_flags
& NOWAIT
)
1339 while (!buf
->done
&& !buf_timed_out
)
1343 m_lcount
= buf
->nbytes
;
1345 m_error
= ETIMEDOUT
;
1347 m_error
= buf
->error
;
1353 // --------------------------------------------------------------
1355 // --------------------------------------------------------------
1357 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1358 wxSockFlags flags
) :
1359 wxSocketBase(flags
, SOCK_SERVER
)
1361 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1363 if (m_fd
== INVALID_SOCKET
)
1367 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
1369 struct sockaddr
*myaddr
;
1372 addr_man
.Build(myaddr
, len
);
1373 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
1376 if (listen(m_fd
, 5) < 0) {
1377 m_fd
= INVALID_SOCKET
;
1382 // --------------------------------------------------------------
1383 // wxSocketServer Accept
1384 // --------------------------------------------------------------
1386 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
1390 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
1393 struct linger linger
;
1395 linger
.l_linger
= 1;
1397 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1400 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1402 if (!(sock
.m_flags
& SPEED
))
1404 unsigned long flag2
= 1;
1405 ioctl(fd2
, FIONBIO
, &flag2
);
1408 sock
.m_type
= SOCK_INTERNAL
;
1410 sock
.m_connected
= TRUE
;
1415 wxSocketBase
*wxSocketServer::Accept()
1417 wxSocketBase
* sock
= new wxSocketBase();
1419 sock
->SetFlags((wxSockFlags
)m_flags
);
1421 if (!AcceptWith(*sock
))
1425 m_handler
->Register(sock
);
1430 // --------------------------------------------------------------
1431 // wxSocketServer callbacks
1432 // --------------------------------------------------------------
1434 void wxSocketServer::OnRequest(wxRequestEvent evt
)
1436 if (evt
== EVT_ACCEPT
)
1438 OldOnNotify(EVT_ACCEPT
);
1442 // --------------------------------------------------------------
1444 // --------------------------------------------------------------
1446 // --------- wxSocketClient CONSTRUCTOR -------------------------
1447 // --------------------------------------------------------------
1448 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
1449 wxSocketBase(_flags
, SOCK_CLIENT
)
1453 // --------------------------------------------------------------
1454 // --------- wxSocketClient DESTRUCTOR --------------------------
1455 // --------------------------------------------------------------
1456 wxSocketClient::~wxSocketClient()
1460 // --------------------------------------------------------------
1461 // --------- wxSocketClient Connect functions -------------------
1462 // --------------------------------------------------------------
1463 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
1465 struct linger linger
;
1470 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1475 m_connected
= FALSE
;
1478 linger
.l_linger
= 5;
1479 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1481 // Stay in touch with the state of things...
1483 unsigned long flag
= 1;
1484 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1486 // Disable the nagle algorithm, which delays sends till the
1487 // buffer is full (or a certain time period has passed?)...
1489 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1491 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
1494 struct sockaddr
*remote
;
1497 addr_man
.Build(remote
, len
);
1499 if (connect(m_fd
, remote
, len
) != 0)
1502 if (!(m_flags
& SPEED
))
1505 ioctl(m_fd
, FIONBIO
, &flag
);
1514 bool wxSocketClient::WaitOnConnect(long seconds
, long microseconds
)
1516 int ret
= _Wait(seconds
, microseconds
, REQ_CONNECT
| REQ_LOST
);
1524 void wxSocketClient::OnRequest(wxRequestEvent evt
)
1526 if (evt
== EVT_CONNECT
)
1531 SetNotify(m_neededreq
& ~REQ_CONNECT
);
1537 OldOnNotify(EVT_CONNECT
);
1543 wxSocketBase::OnRequest(evt
);
1546 /////////////////////////////////////////////////////////////////
1547 // wxSocketHandler ///////////////////////////////////////////////
1548 /////////////////////////////////////////////////////////////////
1550 wxSocketHandler
*wxSocketHandler::master
= NULL
;
1551 #if defined(__WINDOWS__)
1552 static int win_initialized
= 0;
1555 // --------------------------------------------------------------
1556 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1557 // --------------------------------------------------------------
1560 extern "C" int updatestatus(int s
) ;
1562 void wxMacSocketOnRequestProc( void *refcon
, short event
)
1566 wxSocketBase
*sock
= (wxSocketBase
*) refcon
;
1568 wxSocketBase::wxRequestEvent sk_req
;
1576 sk_req
= wxSocketBase::EVT_READ
;
1577 sock
->OnRequest(sk_req
);
1580 sk_req
= wxSocketBase::EVT_WRITE
;
1581 sock
->OnRequest(sk_req
);
1584 sk_req
= wxSocketBase::EVT_LOST
;
1585 sock
->OnRequest(sk_req
);
1588 sk_req
= wxSocketBase::EVT_ACCEPT
;
1589 sock
->OnRequest(sk_req
);
1592 sk_req
= wxSocketBase::EVT_CONNECT
;
1593 sock
->OnRequest(sk_req
);
1598 updatestatus ( sock
->m_fd
) ;
1602 void wxMacSocketHandlerProc( void *refcon
, short event
)
1604 wxMacNetEventsReferences
[wxMacNetEventsTop
] = refcon
;
1605 wxMacNetEventsEvents
[wxMacNetEventsTop
] = event
;
1607 // clumsy construct in order to never have a incorrect wxMacNetEventsTop (above limits)
1609 if ( wxMacNetEventsTop
+ 1 == kwxMacNetEventsMax
)
1610 wxMacNetEventsTop
= 0 ;
1612 wxMacNetEventsTop
++ ;
1618 extern char wxPanelClassName
[];
1620 LRESULT APIENTRY _EXPORT
wxSocketHandlerWndProc(HWND hWnd
, UINT message
,
1621 WPARAM wParam
, LPARAM lParam
)
1623 if(message
==WM_DESTROY
)
1625 ::SetWindowLong(hWnd
, GWL_WNDPROC
, (LONG
) DefWindowProc
);
1626 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1628 wxSocketHandler
*h_sock
= (wxSocketHandler
*)GetWindowLong(hWnd
, GWL_USERDATA
);
1629 wxNode
*node
= h_sock
->smsg_list
->Find(message
);
1631 wxSocketBase::wxRequestEvent sk_req
;
1632 UINT event
= WSAGETSELECTEVENT(lParam
);
1635 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1637 sock
= (wxSocketBase
*)node
->Data();
1641 sk_req
= wxSocketBase::EVT_READ
;
1644 sk_req
= wxSocketBase::EVT_WRITE
;
1647 sk_req
= wxSocketBase::EVT_LOST
;
1650 sk_req
= wxSocketBase::EVT_ACCEPT
;
1653 sk_req
= wxSocketBase::EVT_CONNECT
;
1657 wxFAIL_MSG("invalid socket event");
1661 sock
->OnRequest(sk_req
);
1666 FARPROC wxSocketSubClassProc
= NULL
;
1670 wxSocketHandler::wxSocketHandler()
1672 #if defined(__WINDOWS__)
1673 if (!win_initialized
)
1677 WSAStartup((1 << 8) | 1, &wsaData
);
1678 win_initialized
= 1;
1680 internal
= new wxSockHandlerInternal
;
1681 internal
->sockWin
= ::CreateWindow(wxPanelClassName
, NULL
, 0,
1682 0, 0, 0, 0, NULL
, (HMENU
) NULL
,
1685 // Subclass the window
1686 if (!wxSocketSubClassProc
)
1687 wxSocketSubClassProc
= MakeProcInstance((FARPROC
) wxSocketHandlerWndProc
, wxhInstance
);
1688 ::SetWindowLong(internal
->sockWin
, GWL_WNDPROC
, (LONG
) wxSocketSubClassProc
);
1689 ::SetWindowLong(internal
->sockWin
, GWL_USERDATA
, (LONG
) this);
1691 internal
->firstAvailableMsg
= 5000;
1692 smsg_list
= new wxList(wxKEY_INTEGER
);
1698 signal(SIGPIPE
, SIG_IGN
);
1702 // --------------------------------------------------------------
1703 // --------- wxSocketHandler DESTRUCTOR -------------------------
1704 // --------------------------------------------------------------
1705 wxSocketHandler::~wxSocketHandler()
1707 wxNode
*next_node
, *node
= socks
->First();
1711 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
1714 next_node
= node
->Next();
1724 ::DestroyWindow(internal
->sockWin
);
1726 win_initialized
= 0;
1732 // --------------------------------------------------------------
1733 // --------- wxSocketHandler registering functions --------------
1734 // --------------------------------------------------------------
1736 void wxSocketHandler::Register(wxSocketBase
* sock
)
1740 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next())
1742 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1750 socks
->Append(sock
);
1751 sock
->SetHandler(this);
1752 sock
->SetupCallbacks();
1756 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
1760 for (node
= socks
->First(); node
; node
= node
->Next())
1762 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1767 sock
->DestroyCallbacks();
1768 sock
->SetHandler(NULL
);
1774 unsigned long wxSocketHandler::Count() const
1776 return socks
->Number();
1779 // --------------------------------------------------------------
1780 // --------- wxSocketHandler "big" wait functions ---------------
1781 // --------------------------------------------------------------
1782 void handler_cbk(wxSocketBase
& sock
,
1783 wxSocketBase::wxRequestEvent
WXUNUSED(flags
),
1786 int *a_wait
= (int *)cdata
;
1792 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1796 wxSockWakeUp
s_wake(NULL
, &on_wait
, -2);
1799 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++)
1801 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1805 sock
->SetupCallbacks();
1807 sock
->Callback(handler_cbk
);
1808 sock
->CallbackData((char *)&on_wait
);
1812 s_wake
.Start((seconds
*1000) + (microseconds
/1000), TRUE
);
1817 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++)
1819 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1821 sock
->RestoreState();
1830 void wxSocketHandler::YieldSock()
1834 for (node
= socks
->First(); node
; node
= node
->Next() )
1836 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1840 sock
->SetFlags(wxSocketBase::SPEED
);
1842 sock
->DoRequests(wxSocketBase::EVT_READ
);
1843 sock
->DoRequests(wxSocketBase::EVT_WRITE
);
1845 sock
->RestoreState();
1849 // --------------------------------------------------------------
1850 // --------- wxSocketHandler: create and register the socket ----
1851 // --------------------------------------------------------------
1852 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1853 wxSocketBase::wxSockFlags flags
)
1855 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1861 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1863 wxSocketClient
*client
= new wxSocketClient(flags
);
1870 // --------------------------------------------------------------
1871 // --------- wxSocketHandler: Windows specific methods ----------
1872 // --------------------------------------------------------------
1874 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1876 internal
->firstAvailableMsg
++;
1877 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1878 return internal
->firstAvailableMsg
;
1881 void wxSocketHandler::DestroyMessage(UINT msg
)
1883 wxNode
*node
= smsg_list
->Find(msg
);
1887 HWND
wxSocketHandler::GetHWND() const
1889 return internal
->sockWin
;
1894 bool wxSocketModule::OnInit()
1896 wxSocketHandler::master
= new wxSocketHandler();
1900 void wxSocketModule::OnExit()
1902 delete wxSocketHandler::master
;
1903 wxSocketHandler::master
= NULL
;
1907 void wxMacProcessSocketEvents() ;
1908 void wxMacProcessEvents()
1910 wxMacProcessSocketEvents() ;
1911 (*GUSISpin
)(SP_MISC
, 0) ;
1914 void wxMacProcessSocketEvents()
1916 while ( wxMacNetEventsTop
!= wxMacNetEventsBottom
)
1918 // consume event at wxMacNetEventsBottom
1919 wxMacSocketOnRequestProc(wxMacNetEventsReferences
[wxMacNetEventsBottom
] , wxMacNetEventsEvents
[wxMacNetEventsBottom
] ) ;
1920 wxMacNetEventsBottom
++ ;
1921 if ( wxMacNetEventsBottom
== kwxMacNetEventsMax
)
1922 wxMacNetEventsBottom
= 0 ;