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 # define wxSOCKET_INT socklen_t
549 # define wxSOCKET_INT int
552 // --------------------------------------------------------------
553 // wxSocketBase socket info functions
554 // --------------------------------------------------------------
556 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
558 struct sockaddr my_addr
;
559 wxSOCKET_INT len_addr
= sizeof(my_addr
);
564 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0)
567 addr_man
.Disassemble(&my_addr
, len_addr
);
571 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
573 struct sockaddr my_addr
;
574 wxSOCKET_INT len_addr
= sizeof(my_addr
);
579 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0)
583 addr_man
.Disassemble(&my_addr
, len_addr
);
587 // --------------------------------------------------------------
588 // wxSocketBase wait functions
589 // --------------------------------------------------------------
591 void wxSocketBase::SaveState()
593 wxSockState
*state
= new wxSockState
;
595 state
->cbk_on
= m_cbkon
;
596 state
->cbk_set
= m_neededreq
;
598 state
->cdata
= m_cdata
;
599 state
->flags
= m_flags
;
600 state
->notif
= m_notifyme
;
602 m_states
.Append(state
);
605 void wxSocketBase::RestoreState()
609 node
= m_states
.Last();
613 wxSockState
*state
= (wxSockState
*)node
->Data();
615 SetFlags(state
->flags
);
616 m_neededreq
= state
->cbk_set
;
618 m_cdata
= state
->cdata
;
619 m_notifyme
= state
->notif
;
629 // --------------------------------------------------------------
630 // --------- wxSocketBase wait functions ------------------------
631 // --------------------------------------------------------------
633 bool wxSocketBase::_Wait(long seconds
, long microseconds
, int type
)
635 if ((!m_connected
&& !m_connecting
) || m_fd
< 0)
638 wxSockWakeUp
wakeup(this, &m_waitflags
, 0);
641 SetNotify((wxRequestNotify
)type
);
645 wakeup
.Start((int)(seconds
*1000 + (microseconds
/ 1000)), TRUE
);
647 m_waitflags
= 0x80 | type
;
648 while (m_waitflags
& 0x80)
653 if (m_waitflags
& 0x40)
663 bool wxSocketBase::Wait(long seconds
, long microseconds
)
665 return _Wait(seconds
, microseconds
, REQ_ACCEPT
| REQ_CONNECT
|
666 REQ_READ
| REQ_WRITE
| REQ_LOST
);
669 bool wxSocketBase::WaitForRead(long seconds
, long microseconds
)
671 return _Wait(seconds
, microseconds
, REQ_READ
| REQ_LOST
);
674 bool wxSocketBase::WaitForWrite(long seconds
, long microseconds
)
676 return _Wait(seconds
, microseconds
, REQ_WRITE
);
679 bool wxSocketBase::WaitForLost(long seconds
, long microseconds
)
681 return _Wait(seconds
, microseconds
, REQ_LOST
);
684 // --------------------------------------------------------------
685 // --------- wxSocketBase callback management -------------------
686 // --------------------------------------------------------------
689 void wxPrereadSocket(wxSocketBase
*sock
)
695 got
= recv(sock
->m_fd
, tmp_buf
, 1024, 0);
697 sock
->CreatePushbackAfter(tmp_buf
, got
);
702 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
703 #if defined(__WXMOTIF__) || defined(__WXXT__)
704 static void wx_socket_read(XtPointer client
, int *fid
,
705 XtInputId
*WXUNUSED(id
))
708 static void wx_socket_read(gpointer client
, gint fd
,
709 GdkInputCondition
WXUNUSED(cond
))
713 wxSocketBase
*sock
= (wxSocketBase
*)client
;
717 i
= recv(fd
, &c
, 1, MSG_PEEK
);
719 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
))
721 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
727 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
730 // We can't exit from the GDK main loop because it doesn't accept
731 // destroying input event while we are in a event dispatch.
732 // So we will preread socket and we put the data in the pushback.
733 wxPrereadSocket(sock
);
734 // Then we set the socket as BLOCKING
736 ioctl(fd
, FIONBIO
, &flag
);
741 sock
->OnRequest(wxSocketBase::EVT_READ
);
745 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
751 sock
->OnRequest(wxSocketBase::EVT_LOST
);
756 #if defined(__WXMOTIF__) || defined(__WXXT__)
757 static void wx_socket_write(XtPointer client
, int *WXUNUSED(fid
),
758 XtInputId
*WXUNUSED(id
))
760 static void wx_socket_write(gpointer client
, gint
WXUNUSED(fd
),
761 GdkInputCondition
WXUNUSED(cond
))
764 wxSocketBase
*sock
= (wxSocketBase
*)client
;
766 if (!sock
->IsConnected())
767 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
769 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
774 Notify_value
wx_sock_read_xview (Notify_client client
, int fd
)
776 wxSocketBase
*sock
= (wxSocketBase
*)client
;
780 i
= recv(fd
, &c
, 1, MSG_PEEK
);
782 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
))
784 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
791 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
792 return (Notify_value
) FALSE
;
794 sock
->OnRequest(wxSocketBase::EVT_READ
);
798 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
801 sock
->OnRequest(wxSocketBase::EVT_LOST
);
804 return (Notify_value
) FALSE
;
807 Notify_value
wx_sock_write_xview (Notify_client client
, int fd
)
809 wxSocketBase
*sock
= (wxSocketBase
*)client
;
811 if (!sock
->IsConnected())
812 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
814 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
816 return (Notify_value
) TRUE
;
820 wxSocketBase::wxRequestNotify
wxSocketBase::EventToNotify(wxRequestEvent evt
)
840 void wxSocketBase::SetFlags(wxSockFlags _flags
)
845 unsigned long flag
= 0;
846 ioctl(m_fd
, FIONBIO
, &flag
);
848 // SPEED and WAITALL are antagonists.
849 m_flags
= (wxSockFlags
)(m_flags
& ~WAITALL
);
855 unsigned long flag
= 1;
856 ioctl(m_fd
, FIONBIO
, &flag
);
860 void wxSocketBase::SetNotify(wxRequestNotify flags
)
862 wxRequestNotify old_needed_req
= m_neededreq
;
863 if (flags
& REQ_ACCEPT
)
865 /* Check if server */
866 if (!(GetClassInfo()->IsKindOf(CLASSINFO(wxSocketServer
))))
867 flags
&= ~REQ_ACCEPT
;
872 if (m_cbkon && old_needed_req != flags) seems to be wrong, Robert Roebling
876 if (old_needed_req
!= flags
)
880 void wxSocketBase::SetupCallbacks()
882 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| (m_flags
& SPEED
))
885 #if defined(__WXMOTIF__) || defined(__WXXT__)
886 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
))
888 if (m_internal
->sock_inputid
<= 0)
890 m_internal
->sock_inputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
891 (XtPointer
*) XtInputReadMask
,
892 (XtInputCallbackProc
) wx_socket_read
,
898 if (m_internal
->sock_inputid
> 0)
900 XtRemoveInput(m_internal
->sock_inputid
);
901 m_internal
->sock_inputid
= 0;
905 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
))
907 if (m_internal
->sock_outputid
<= 0)
909 m_internal
->sock_outputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
910 (XtPointer
*) XtInputWriteMask
,
911 (XtInputCallbackProc
) wx_socket_write
,
917 if (m_internal
->sock_outputid
> 0)
919 XtRemoveInput(m_internal
->sock_outputid
);
920 m_internal
->sock_outputid
= 0;
927 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
))
929 if (m_internal
->sock_inputid
<= 0)
931 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_READ
,
932 wx_socket_read
, (gpointer
)this);
937 if (m_internal
->sock_inputid
> 0)
940 gdk_input_remove(m_internal->sock_inputid);
941 m_internal->sock_inputid = 0;
946 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
))
948 if (m_internal
->sock_outputid
<= 0)
950 m_internal
->sock_outputid
= gdk_input_add(m_fd
, GDK_INPUT_WRITE
,
951 wx_socket_write
, (gpointer
)this);
956 if (m_internal
->sock_outputid
> 0)
959 gdk_input_remove(m_internal->sock_outputid);
960 m_internal->sock_outputid = 0;
970 if (m_neededreq
& REQ_READ
)
972 if (m_neededreq
& REQ_WRITE
)
974 if (m_neededreq
& REQ_LOST
)
976 if (m_neededreq
& REQ_ACCEPT
)
978 if (m_neededreq
& REQ_CONNECT
)
981 if (!m_internal
->my_msg
)
982 m_internal
->my_msg
= m_handler
->NewMessage(this);
983 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), m_internal
->my_msg
, mask
);
988 if (m_neededreq
& REQ_READ
)
990 if (m_neededreq
& REQ_WRITE
)
992 if (m_neededreq
& REQ_LOST
)
994 if (m_neededreq
& REQ_ACCEPT
)
996 if (m_neededreq
& REQ_CONNECT
)
999 GUSISetReference( m_fd
,mask
, this ) ;
1000 unsigned long flag
= 1;
1001 ioctl(m_fd
, FIONBIO
, &flag
);
1004 m_processing
= FALSE
;
1007 void wxSocketBase::DestroyCallbacks()
1009 if (!m_cbkon
|| !m_handler
)
1013 m_processing
= FALSE
;
1014 #if defined(__WXMOTIF__) || defined(__WXXT__)
1015 if (m_internal
->sock_inputid
> 0)
1016 XtRemoveInput(m_internal
->sock_inputid
);
1017 m_internal
->sock_inputid
= 0;
1018 if (m_internal
->sock_outputid
> 0)
1019 XtRemoveInput(m_internal
->sock_outputid
);
1020 m_internal
->sock_outputid
= 0;
1023 if (m_internal
->sock_inputid
> 0)
1024 gdk_input_remove(m_internal
->sock_inputid
);
1025 m_internal
->sock_inputid
= 0;
1026 if (m_internal
->sock_outputid
> 0)
1027 gdk_input_remove(m_internal
->sock_outputid
);
1028 m_internal
->sock_outputid
= 0;
1031 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), 0, 0);
1034 GUSISetReference( m_fd
, 0 , 0 ) ;
1035 int bottom
= wxMacNetEventsBottom
;
1036 while ( wxMacNetEventsTop
!= bottom
)
1038 // set all events that reference this socket to nil
1039 if ( wxMacNetEventsReferences
[bottom
] == (void*) this )
1040 wxMacNetEventsReferences
[bottom
] = NULL
;
1042 if ( bottom
== kwxMacNetEventsMax
)
1045 SetFlags( m_flags
) ;
1049 void wxSocketBase::Notify(bool notify
)
1051 if (m_notifyme
== notify
)
1057 m_notifyme
= notify
;
1060 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
1062 wxRequestNotify req_notif
= EventToNotify(req_evt
);
1064 // Mask the current event
1065 SetNotify(m_neededreq
& ~req_notif
);
1067 if (req_evt
<= EVT_WRITE
&& DoRequests(req_evt
))
1070 if (m_waitflags
& 0xF0)
1073 if ((m_waitflags
& 0x0F) == req_evt
)
1083 if (req_evt
== EVT_LOST
)
1085 m_connected
= FALSE
;
1089 OldOnNotify(req_evt
);
1092 SetNotify(m_neededreq
| req_notif
);
1095 wxSocketEvent::wxSocketEvent(int id
)
1098 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
1103 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
1105 wxSocketEvent
event(m_id
);
1107 event
.SetEventObject(this);
1108 event
.m_skevt
= evt
;
1109 ProcessEvent(event
);
1112 m_cbk(*this, evt
, m_cdata
);
1115 // --------------------------------------------------------------
1116 // --------- wxSocketBase functions [Callback, CallbackData] ----
1117 // --------------------------------------------------------------
1119 wxSocketBase::wxSockCbk
wxSocketBase::Callback(wxSocketBase::wxSockCbk _cbk
)
1121 wxSockCbk old_cbk
= m_cbk
;
1127 char *wxSocketBase::CallbackData(char *cdata_
)
1129 char *old_cdata
= m_cdata
;
1135 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
1137 SetNextHandler(&h_evt
);
1141 // --------------------------------------------------------------
1142 // --------- wxSocketBase pushback library ----------------------
1143 // --------------------------------------------------------------
1145 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
1149 if (m_unread
!= NULL
)
1150 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
1152 m_unread
= (char *) malloc(size
);
1153 curr_pos
= m_unread
+ m_unrd_size
;
1155 memcpy(curr_pos
, buffer
, size
);
1156 m_unrd_size
+= size
;
1159 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
1161 char *curr_pos
, *new_buf
;
1163 new_buf
= (char *) malloc(m_unrd_size
+size
);
1164 curr_pos
= new_buf
+ size
;
1166 memcpy(new_buf
, buffer
, size
);
1167 if (m_unrd_size
!= 0) {
1168 memcpy(curr_pos
, m_unread
, m_unrd_size
);
1172 m_unrd_size
+= size
;
1175 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
1180 if (size
> m_unrd_size
)
1182 memcpy(buffer
, m_unread
, size
);
1185 m_unrd_size
-= size
;
1186 if (m_unrd_size
== 0) {
1195 // --------------------------------------------------------------
1196 // --------- wxSocketBase "multi-thread" core -------------------
1197 // --------------------------------------------------------------
1199 bool wxSocketBase::DoRequests(wxRequestEvent req_flag
)
1201 wxNode
*node
= req_list
[req_flag
].First();
1208 SockRequest
*req
= (SockRequest
*)node
->Data();
1216 ret
= recv(m_fd
, req
->buffer
, req
->size
,
1217 (req
->type
== EVT_PEEK
) ? MSG_PEEK
: 0);
1225 if ((len
< req
->size
) && (m_flags
& WAITALL
))
1230 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1231 req_list
[req_flag
].Insert(req
);
1241 ret
= send(m_fd
, req
->buffer
, req
->size
, 0);
1249 if ((len
< req
->size
) && (m_flags
& WAITALL
))
1254 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1255 req_list
[req_flag
].Insert(req
);
1270 void wxSocketBase::WantSpeedBuffer(char *buffer
, size_t nbytes
,
1279 ret
= recv(m_fd
, buffer
, nbytes
,
1280 (evt
== EVT_PEEK
) ? MSG_PEEK
: 0);
1283 ret
= send(m_fd
, buffer
, nbytes
, 0);
1298 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
1303 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
1306 if (m_flags
& SPEED
)
1308 WantSpeedBuffer(buffer
, nbytes
, evt
);
1312 SockRequest
*buf
= new SockRequest
;
1313 wxSockWakeUp
s_wake(NULL
, (int *)&buf_timed_out
, (int)TRUE
);
1316 req_list
[evt
].Append(buf
);
1319 SetNotify(REQ_LOST
| EventToNotify(evt
));
1321 buf
->buffer
= buffer
;
1326 buf
->auto_wakeup
= &s_wake
;
1328 buf_timed_out
= FALSE
;
1330 s_wake
.Start(m_timeout
*1000, TRUE
);
1331 if (m_flags
& NOWAIT
)
1337 while (!buf
->done
&& !buf_timed_out
)
1341 m_lcount
= buf
->nbytes
;
1343 m_error
= ETIMEDOUT
;
1345 m_error
= buf
->error
;
1351 // --------------------------------------------------------------
1353 // --------------------------------------------------------------
1355 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1356 wxSockFlags flags
) :
1357 wxSocketBase(flags
, SOCK_SERVER
)
1359 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1361 if (m_fd
== INVALID_SOCKET
)
1365 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
1367 struct sockaddr
*myaddr
;
1370 addr_man
.Build(myaddr
, len
);
1371 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
1374 if (listen(m_fd
, 5) < 0) {
1375 m_fd
= INVALID_SOCKET
;
1380 // --------------------------------------------------------------
1381 // wxSocketServer Accept
1382 // --------------------------------------------------------------
1384 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
1388 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
1391 struct linger linger
;
1393 linger
.l_linger
= 1;
1395 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1398 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1400 if (!(sock
.m_flags
& SPEED
))
1402 unsigned long flag2
= 1;
1403 ioctl(fd2
, FIONBIO
, &flag2
);
1406 sock
.m_type
= SOCK_INTERNAL
;
1408 sock
.m_connected
= TRUE
;
1413 wxSocketBase
*wxSocketServer::Accept()
1415 wxSocketBase
* sock
= new wxSocketBase();
1417 sock
->SetFlags((wxSockFlags
)m_flags
);
1419 if (!AcceptWith(*sock
))
1423 m_handler
->Register(sock
);
1428 // --------------------------------------------------------------
1429 // wxSocketServer callbacks
1430 // --------------------------------------------------------------
1432 void wxSocketServer::OnRequest(wxRequestEvent evt
)
1434 if (evt
== EVT_ACCEPT
)
1436 OldOnNotify(EVT_ACCEPT
);
1440 // --------------------------------------------------------------
1442 // --------------------------------------------------------------
1444 // --------- wxSocketClient CONSTRUCTOR -------------------------
1445 // --------------------------------------------------------------
1446 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
1447 wxSocketBase(_flags
, SOCK_CLIENT
)
1451 // --------------------------------------------------------------
1452 // --------- wxSocketClient DESTRUCTOR --------------------------
1453 // --------------------------------------------------------------
1454 wxSocketClient::~wxSocketClient()
1458 // --------------------------------------------------------------
1459 // --------- wxSocketClient Connect functions -------------------
1460 // --------------------------------------------------------------
1461 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
1463 struct linger linger
;
1468 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1473 m_connected
= FALSE
;
1476 linger
.l_linger
= 5;
1477 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1479 // Stay in touch with the state of things...
1481 unsigned long flag
= 1;
1482 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1484 // Disable the nagle algorithm, which delays sends till the
1485 // buffer is full (or a certain time period has passed?)...
1487 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1489 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
1492 struct sockaddr
*remote
;
1495 addr_man
.Build(remote
, len
);
1497 if (connect(m_fd
, remote
, len
) != 0)
1500 if (!(m_flags
& SPEED
))
1503 ioctl(m_fd
, FIONBIO
, &flag
);
1512 bool wxSocketClient::WaitOnConnect(long seconds
, long microseconds
)
1514 int ret
= _Wait(seconds
, microseconds
, REQ_CONNECT
| REQ_LOST
);
1522 void wxSocketClient::OnRequest(wxRequestEvent evt
)
1524 if (evt
== EVT_CONNECT
)
1529 SetNotify(m_neededreq
& ~REQ_CONNECT
);
1535 OldOnNotify(EVT_CONNECT
);
1541 wxSocketBase::OnRequest(evt
);
1544 /////////////////////////////////////////////////////////////////
1545 // wxSocketHandler ///////////////////////////////////////////////
1546 /////////////////////////////////////////////////////////////////
1548 wxSocketHandler
*wxSocketHandler::master
= NULL
;
1549 #if defined(__WINDOWS__)
1550 static int win_initialized
= 0;
1553 // --------------------------------------------------------------
1554 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1555 // --------------------------------------------------------------
1558 extern "C" int updatestatus(int s
) ;
1560 void wxMacSocketOnRequestProc( void *refcon
, short event
)
1564 wxSocketBase
*sock
= (wxSocketBase
*) refcon
;
1566 wxSocketBase::wxRequestEvent sk_req
;
1574 sk_req
= wxSocketBase::EVT_READ
;
1575 sock
->OnRequest(sk_req
);
1578 sk_req
= wxSocketBase::EVT_WRITE
;
1579 sock
->OnRequest(sk_req
);
1582 sk_req
= wxSocketBase::EVT_LOST
;
1583 sock
->OnRequest(sk_req
);
1586 sk_req
= wxSocketBase::EVT_ACCEPT
;
1587 sock
->OnRequest(sk_req
);
1590 sk_req
= wxSocketBase::EVT_CONNECT
;
1591 sock
->OnRequest(sk_req
);
1596 updatestatus ( sock
->m_fd
) ;
1600 void wxMacSocketHandlerProc( void *refcon
, short event
)
1602 wxMacNetEventsReferences
[wxMacNetEventsTop
] = refcon
;
1603 wxMacNetEventsEvents
[wxMacNetEventsTop
] = event
;
1605 // clumsy construct in order to never have a incorrect wxMacNetEventsTop (above limits)
1607 if ( wxMacNetEventsTop
+ 1 == kwxMacNetEventsMax
)
1608 wxMacNetEventsTop
= 0 ;
1610 wxMacNetEventsTop
++ ;
1616 extern char wxPanelClassName
[];
1618 LRESULT APIENTRY _EXPORT
wxSocketHandlerWndProc(HWND hWnd
, UINT message
,
1619 WPARAM wParam
, LPARAM lParam
)
1621 if(message
==WM_DESTROY
)
1623 ::SetWindowLong(hWnd
, GWL_WNDPROC
, (LONG
) DefWindowProc
);
1624 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1626 wxSocketHandler
*h_sock
= (wxSocketHandler
*)GetWindowLong(hWnd
, GWL_USERDATA
);
1627 wxNode
*node
= h_sock
->smsg_list
->Find(message
);
1629 wxSocketBase::wxRequestEvent sk_req
;
1630 UINT event
= WSAGETSELECTEVENT(lParam
);
1633 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1635 sock
= (wxSocketBase
*)node
->Data();
1639 sk_req
= wxSocketBase::EVT_READ
;
1642 sk_req
= wxSocketBase::EVT_WRITE
;
1645 sk_req
= wxSocketBase::EVT_LOST
;
1648 sk_req
= wxSocketBase::EVT_ACCEPT
;
1651 sk_req
= wxSocketBase::EVT_CONNECT
;
1655 wxFAIL_MSG("invalid socket event");
1659 sock
->OnRequest(sk_req
);
1664 FARPROC wxSocketSubClassProc
= NULL
;
1668 wxSocketHandler::wxSocketHandler()
1670 #if defined(__WINDOWS__)
1671 if (!win_initialized
)
1675 WSAStartup((1 << 8) | 1, &wsaData
);
1676 win_initialized
= 1;
1678 internal
= new wxSockHandlerInternal
;
1679 internal
->sockWin
= ::CreateWindow(wxPanelClassName
, NULL
, 0,
1680 0, 0, 0, 0, NULL
, (HMENU
) NULL
,
1683 // Subclass the window
1684 if (!wxSocketSubClassProc
)
1685 wxSocketSubClassProc
= MakeProcInstance((FARPROC
) wxSocketHandlerWndProc
, wxhInstance
);
1686 ::SetWindowLong(internal
->sockWin
, GWL_WNDPROC
, (LONG
) wxSocketSubClassProc
);
1687 ::SetWindowLong(internal
->sockWin
, GWL_USERDATA
, (LONG
) this);
1689 internal
->firstAvailableMsg
= 5000;
1690 smsg_list
= new wxList(wxKEY_INTEGER
);
1696 signal(SIGPIPE
, SIG_IGN
);
1700 // --------------------------------------------------------------
1701 // --------- wxSocketHandler DESTRUCTOR -------------------------
1702 // --------------------------------------------------------------
1703 wxSocketHandler::~wxSocketHandler()
1705 wxNode
*next_node
, *node
= socks
->First();
1709 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
1712 next_node
= node
->Next();
1722 ::DestroyWindow(internal
->sockWin
);
1724 win_initialized
= 0;
1730 // --------------------------------------------------------------
1731 // --------- wxSocketHandler registering functions --------------
1732 // --------------------------------------------------------------
1734 void wxSocketHandler::Register(wxSocketBase
* sock
)
1738 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next())
1740 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1748 socks
->Append(sock
);
1749 sock
->SetHandler(this);
1750 sock
->SetupCallbacks();
1754 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
1758 for (node
= socks
->First(); node
; node
= node
->Next())
1760 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1765 sock
->DestroyCallbacks();
1766 sock
->SetHandler(NULL
);
1772 unsigned long wxSocketHandler::Count() const
1774 return socks
->Number();
1777 // --------------------------------------------------------------
1778 // --------- wxSocketHandler "big" wait functions ---------------
1779 // --------------------------------------------------------------
1780 void handler_cbk(wxSocketBase
& sock
,
1781 wxSocketBase::wxRequestEvent
WXUNUSED(flags
),
1784 int *a_wait
= (int *)cdata
;
1790 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1794 wxSockWakeUp
s_wake(NULL
, &on_wait
, -2);
1797 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++)
1799 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1803 sock
->SetupCallbacks();
1805 sock
->Callback(handler_cbk
);
1806 sock
->CallbackData((char *)&on_wait
);
1810 s_wake
.Start((seconds
*1000) + (microseconds
/1000), TRUE
);
1815 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++)
1817 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1819 sock
->RestoreState();
1828 void wxSocketHandler::YieldSock()
1832 for (node
= socks
->First(); node
; node
= node
->Next() )
1834 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1838 sock
->SetFlags(wxSocketBase::SPEED
);
1840 sock
->DoRequests(wxSocketBase::EVT_READ
);
1841 sock
->DoRequests(wxSocketBase::EVT_WRITE
);
1843 sock
->RestoreState();
1847 // --------------------------------------------------------------
1848 // --------- wxSocketHandler: create and register the socket ----
1849 // --------------------------------------------------------------
1850 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1851 wxSocketBase::wxSockFlags flags
)
1853 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1859 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1861 wxSocketClient
*client
= new wxSocketClient(flags
);
1868 // --------------------------------------------------------------
1869 // --------- wxSocketHandler: Windows specific methods ----------
1870 // --------------------------------------------------------------
1872 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1874 internal
->firstAvailableMsg
++;
1875 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1876 return internal
->firstAvailableMsg
;
1879 void wxSocketHandler::DestroyMessage(UINT msg
)
1881 wxNode
*node
= smsg_list
->Find(msg
);
1885 HWND
wxSocketHandler::GetHWND() const
1887 return internal
->sockWin
;
1892 bool wxSocketModule::OnInit()
1894 wxSocketHandler::master
= new wxSocketHandler();
1898 void wxSocketModule::OnExit()
1900 delete wxSocketHandler::master
;
1901 wxSocketHandler::master
= NULL
;
1905 void wxMacProcessSocketEvents() ;
1906 void wxMacProcessEvents()
1908 wxMacProcessSocketEvents() ;
1909 (*GUSISpin
)(SP_MISC
, 0) ;
1912 void wxMacProcessSocketEvents()
1914 while ( wxMacNetEventsTop
!= wxMacNetEventsBottom
)
1916 // consume event at wxMacNetEventsBottom
1917 wxMacSocketOnRequestProc(wxMacNetEventsReferences
[wxMacNetEventsBottom
] , wxMacNetEventsEvents
[wxMacNetEventsBottom
] ) ;
1918 wxMacNetEventsBottom
++ ;
1919 if ( wxMacNetEventsBottom
== kwxMacNetEventsMax
)
1920 wxMacNetEventsBottom
= 0 ;