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"
18 // For compilers that support precompilation, includes "wx.h".
19 #include "wx/wxprec.h"
25 /////////////////////////////////////////////////////////////////////////////
27 /////////////////////////////////////////////////////////////////////////////
29 #include <wx/object.h>
30 #include <wx/string.h>
34 // Not enough OS behaviour defined for wxStubs
41 /////////////////////////////////////////////////////////////////////////////
42 // System specific headers
43 /////////////////////////////////////////////////////////////////////////////
44 #if defined(__WINDOWS__)
53 #include <sys/socket.h>
55 #include <sys/ioctl.h>
61 #include <sys/filio.h>
73 #if defined(__WXMOTIF__) || defined(__WXXT__)
74 #include <X11/Intrinsic.h>
76 /////////////////////////////
77 // Needs internal variables
78 /////////////////////////////
80 #define Uses_XtIntrinsic
85 #if defined(__WXGTK__)
89 /////////////////////////////////////////////////////////////////////////////
91 /////////////////////////////////////////////////////////////////////////////
92 #include "wx/module.h"
93 #define WXSOCK_INTERNAL
94 #include "wx/sckaddr.h"
95 #include "wx/socket.h"
97 /////////////////////////////////////////////////////////////////////////////
98 // Some patch ///// BEGIN
99 /////////////////////////////////////////////////////////////////////////////
101 #define close closesocket
102 #define ioctl ioctlsocket
106 #define errno WSAGetLastError()
110 #define EWOULDBLOCK WSAEWOULDBLOCK
111 #define ETIMEDOUT WSAETIMEDOUT
113 #define EINTR WSAEINTR
117 #define INVALID_SOCKET -1
121 #define wxAPP_CONTEXT ((XtAppContext)wxTheApp->GetAppContext())
125 // This is an MS TCP/IP routine and is not needed here. Some WinSock
126 // implementations (such as PC-NFS) will require you to include this
127 // or a similar routine (see appendix in WinSock doc or help file).
129 #if defined( NEED_WSAFDIsSet ) || defined( _MSC_VER )
130 int PASCAL FAR
__WSAFDIsSet(SOCKET fd
, fd_set FAR
*set
)
132 int i
= set
->fd_count
;
136 if (set
->fd_array
[i
] == fd
)
145 #if defined(__WINDOWS__)
146 #define PROCESS_EVENTS() wxYield()
147 #elif defined(__WXXT__) || defined(__WXMOTIF__)
148 #define PROCESS_EVENTS() XtAppProcessEvent(wxAPP_CONTEXT, XtIMAll)
149 #elif defined(__WXGTK__)
150 #define PROCESS_EVENTS() gtk_main_iteration()
153 /////////////////////////////////////////////////////////////////////////////
154 // Some patch ///// END
155 /////////////////////////////////////////////////////////////////////////////
157 // --------------------------------------------------------------
159 // --------------------------------------------------------------
160 class wxSocketModule
: public wxModule
162 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
169 // --------------------------------------------------------------
171 // --------------------------------------------------------------
172 #if !USE_SHARED_LIBRARY
173 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
174 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
175 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
176 IMPLEMENT_CLASS(wxSocketHandler
, wxObject
)
177 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
178 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)
181 class wxSockWakeUp
: public wxTimer
188 wxSockWakeUp(wxSocketBase
*_sock
, int *id
, int new_val
)
190 my_id
= id
; n_val
= new_val
;
193 virtual void Notify()
196 if (sock
) sock
->Notify(FALSE
);
201 class SockRequest
: public wxObject
208 wxSockWakeUp
*auto_wakeup
;
209 wxSocketBase::wxRequestNotify type
;
213 /////////////////////////////////////////////////////////////////////////////
214 // Some internal define
215 /////////////////////////////////////////////////////////////////////////////
217 // --------------------------------------------------------------
218 // --------- wxSocketBase CONSTRUCTOR ---------------------------
219 // --------------------------------------------------------------
220 wxSocketBase::wxSocketBase(wxSocketBase::wxSockFlags _flags
,
221 wxSocketBase::wxSockType _type
) :
223 m_flags(_flags
), m_type(_type
), m_connected(FALSE
), m_connecting(FALSE
),
224 m_fd(INVALID_SOCKET
), m_waitflags(0), m_cbk(0), m_cdata(0), m_id(-1),
226 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
228 m_unread(NULL
), m_unrd_size(0),
230 m_timeout(3600), m_wantbuf(0)
232 m_internal
= new wxSockInternal
;
233 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
234 m_internal
->sock_inputid
= 0;
235 m_internal
->sock_outputid
= 0;
236 m_internal
->sock_exceptid
= 0;
239 m_internal
->my_msg
= 0;
243 wxSocketBase::wxSocketBase() :
245 m_flags(WAITALL
), m_type(SOCK_UNINIT
), m_connected(FALSE
),
246 m_connecting(FALSE
), m_fd(INVALID_SOCKET
), m_waitflags(0),
247 m_cbk(0), m_cdata(0),
248 m_id(-1), m_handler(0),
249 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
251 m_unread(NULL
), m_unrd_size(0),
253 m_timeout(3600), m_wantbuf(0)
255 m_internal
= new wxSockInternal
;
256 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
257 m_internal
->sock_inputid
= 0;
258 m_internal
->sock_outputid
= 0;
259 m_internal
->sock_exceptid
= 0;
262 m_internal
->my_msg
= 0;
266 // --------------------------------------------------------------
268 // --------------------------------------------------------------
270 wxSocketBase::~wxSocketBase()
280 if (m_internal
->my_msg
)
281 m_handler
->DestroyMessage(m_internal
->my_msg
);
283 m_handler
->UnRegister(this);
285 m_states
.DeleteContents(TRUE
);
290 bool wxSocketBase::Close()
292 if (m_fd
!= INVALID_SOCKET
)
294 for (int i
=0;i
<3;i
++)
296 wxNode
*n
, *node
= req_list
[i
].First();
300 SockRequest
*req
= (SockRequest
*)node
->Data();
312 m_fd
= INVALID_SOCKET
;
319 // --------------------------------------------------------------
320 // wxSocketBase base IO function
321 // --------------------------------------------------------------
323 wxSocketBase
& wxSocketBase::Read(char* buffer
, size_t nbytes
)
325 m_lcount
= GetPushback(buffer
, nbytes
, FALSE
);
327 // If we have got the whole needed buffer or if we don't want to
328 // wait then it returns immediately.
329 if (!nbytes
|| (m_lcount
&& !(m_flags
& WAITALL
)) )
332 WantBuffer(buffer
, nbytes
, EVT_READ
);
337 wxSocketBase
& wxSocketBase::Peek(char* buffer
, size_t nbytes
)
339 size_t nbytes_old
= nbytes
;
341 nbytes
-= GetPushback(buffer
, nbytes
, TRUE
);
344 m_lcount
= nbytes_old
;
348 WantBuffer(buffer
, nbytes
, EVT_PEEK
);
353 wxSocketBase
& wxSocketBase::Write(const char *buffer
, size_t nbytes
)
355 WantBuffer((char *)buffer
, nbytes
, EVT_WRITE
);
359 wxSocketBase
& wxSocketBase::ReadMsg(char* buffer
, size_t nbytes
)
362 size_t len
, len2
, sig
;
364 Read((char *)&msg
, sizeof(msg
));
365 if (m_lcount
!= sizeof(msg
))
368 sig
= msg
.sig
[0] & 0xff;
369 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
370 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
371 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
373 if (sig
!= 0xfeeddead)
375 len
= msg
.len
[0] & 0xff;
376 len
|= (size_t)(msg
.len
[1] & 0xff) << 8;
377 len
|= (size_t)(msg
.len
[2] & 0xff) << 16;
378 len
|= (size_t)(msg
.len
[3] & 0xff) << 24;
385 if (Read(buffer
, len
).LastCount() != len
)
387 if (len2
&& (Read(NULL
, len2
).LastCount() != len2
))
389 if (Read((char *)&msg
, sizeof(msg
)).LastCount() != sizeof(msg
))
392 sig
= msg
.sig
[0] & 0xff;
393 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
394 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
395 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
397 if (sig
!= 0xdeadfeed)
403 wxSocketBase
& wxSocketBase::WriteMsg(const char *buffer
, size_t nbytes
)
407 msg
.sig
[0] = (char) 0xad;
408 msg
.sig
[1] = (char) 0xde;
409 msg
.sig
[2] = (char) 0xed;
410 msg
.sig
[3] = (char) 0xfe;
412 msg
.len
[0] = (char) nbytes
& 0xff;
413 msg
.len
[1] = (char) (nbytes
>> 8) & 0xff;
414 msg
.len
[2] = (char) (nbytes
>> 16) & 0xff;
415 msg
.len
[3] = (char) (nbytes
>> 24) & 0xff;
417 if (Write((char *)&msg
, sizeof(msg
)).LastCount() < sizeof(msg
))
419 if (Write(buffer
, nbytes
).LastCount() < nbytes
)
422 msg
.sig
[0] = (char) 0xed;
423 msg
.sig
[1] = (char) 0xfe;
424 msg
.sig
[2] = (char) 0xad;
425 msg
.sig
[3] = (char) 0xde;
426 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
427 Write((char *)&msg
, sizeof(msg
));
432 wxSocketBase
& wxSocketBase::Unread(const char *buffer
, size_t nbytes
)
434 CreatePushbackAfter(buffer
, nbytes
);
438 bool wxSocketBase::IsData() const
451 FD_SET(m_fd
, &sock_set
);
452 select(FD_SETSIZE
, &sock_set
, NULL
, NULL
, &tv
);
453 return (FD_ISSET(m_fd
, &sock_set
) != 0);
456 // ---------------------------------------------------------------------
457 // --------- wxSocketBase Discard(): deletes all byte in the input queue
458 // ---------------------------------------------------------------------
459 void wxSocketBase::Discard()
461 #define MAX_BUFSIZE (10*1024)
462 char *my_data
= new char[MAX_BUFSIZE
];
463 size_t recv_size
= MAX_BUFSIZE
;
466 SetFlags((wxSockFlags
)(NOWAIT
| SPEED
));
468 while (recv_size
== MAX_BUFSIZE
)
470 recv_size
= Read(my_data
, MAX_BUFSIZE
).LastCount();
479 // If what? Who seems to need unsigned int?
480 // BTW uint isn't even defined on wxMSW for VC++ for some reason. Even if it
481 // were, getpeername/getsockname don't take unsigned int*, they take int*.
483 #define wxSOCKET_INT unsigned int
485 #define wxSOCKET_INT int
488 // --------------------------------------------------------------
489 // wxSocketBase socket info functions
490 // --------------------------------------------------------------
492 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
494 struct sockaddr my_addr
;
495 wxSOCKET_INT len_addr
= sizeof(my_addr
);
500 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0)
503 addr_man
.Disassemble(&my_addr
, len_addr
);
507 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
509 struct sockaddr my_addr
;
510 wxSOCKET_INT len_addr
= sizeof(my_addr
);
515 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0)
519 addr_man
.Disassemble(&my_addr
, len_addr
);
523 // --------------------------------------------------------------
524 // wxSocketBase wait functions
525 // --------------------------------------------------------------
527 void wxSocketBase::SaveState()
529 wxSockState
*state
= new wxSockState
;
531 state
->cbk_on
= m_cbkon
;
532 state
->cbk_set
= m_neededreq
;
534 state
->cdata
= m_cdata
;
535 state
->flags
= m_flags
;
536 state
->notif
= m_notifyme
;
538 m_states
.Append(state
);
541 void wxSocketBase::RestoreState()
545 node
= m_states
.Last();
549 wxSockState
*state
= (wxSockState
*)node
->Data();
551 SetFlags(state
->flags
);
552 m_neededreq
= state
->cbk_set
;
554 m_cdata
= state
->cdata
;
555 m_notifyme
= state
->notif
;
565 // --------------------------------------------------------------
566 // --------- wxSocketBase wait functions ------------------------
567 // --------------------------------------------------------------
569 bool wxSocketBase::_Wait(long seconds
, long microseconds
, int type
)
571 if ((!m_connected
&& !m_connecting
) || m_fd
< 0)
574 wxSockWakeUp
wakeup(this, &m_waitflags
, 0);
577 SetNotify((wxRequestNotify
)type
);
581 wakeup
.Start((int)(seconds
*1000 + (microseconds
/ 1000)), TRUE
);
583 m_waitflags
= 0x80 | type
;
584 while (m_waitflags
& 0x80)
589 if (m_waitflags
& 0x40)
599 bool wxSocketBase::Wait(long seconds
, long microseconds
)
601 return _Wait(seconds
, microseconds
, REQ_ACCEPT
| REQ_CONNECT
|
602 REQ_READ
| REQ_WRITE
| REQ_LOST
);
605 bool wxSocketBase::WaitForRead(long seconds
, long microseconds
)
607 return _Wait(seconds
, microseconds
, REQ_READ
| REQ_LOST
);
610 bool wxSocketBase::WaitForWrite(long seconds
, long microseconds
)
612 return _Wait(seconds
, microseconds
, REQ_WRITE
);
615 bool wxSocketBase::WaitForLost(long seconds
, long microseconds
)
617 return _Wait(seconds
, microseconds
, REQ_LOST
);
620 // --------------------------------------------------------------
621 // --------- wxSocketBase callback management -------------------
622 // --------------------------------------------------------------
624 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
625 #if defined(__WXMOTIF__) || defined(__WXXT__)
626 static void wx_socket_read(XtPointer client
, int *fid
,
627 XtInputId
*WXUNUSED(id
))
630 static void wx_socket_read(gpointer client
, gint fd
,
631 GdkInputCondition
WXUNUSED(cond
))
635 wxSocketBase
*sock
= (wxSocketBase
*)client
;
639 i
= recv(fd
, &c
, 1, MSG_PEEK
);
641 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
))
643 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
649 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
654 sock
->OnRequest(wxSocketBase::EVT_READ
);
658 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
664 sock
->OnRequest(wxSocketBase::EVT_LOST
);
669 #if defined(__WXMOTIF__) || defined(__WXXT__)
670 static void wx_socket_write(XtPointer client
, int *WXUNUSED(fid
),
671 XtInputId
*WXUNUSED(id
))
673 static void wx_socket_write(gpointer client
, gint
WXUNUSED(fd
),
674 GdkInputCondition
WXUNUSED(cond
))
677 wxSocketBase
*sock
= (wxSocketBase
*)client
;
679 if (!sock
->IsConnected())
680 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
682 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
687 Notify_value
wx_sock_read_xview (Notify_client client
, int fd
)
689 wxSocketBase
*sock
= (wxSocketBase
*)client
;
693 i
= recv(fd
, &c
, 1, MSG_PEEK
);
695 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
))
697 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
704 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
705 return (Notify_value
) FALSE
;
707 sock
->OnRequest(wxSocketBase::EVT_READ
);
711 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
714 sock
->OnRequest(wxSocketBase::EVT_LOST
);
717 return (Notify_value
) FALSE
;
720 Notify_value
wx_sock_write_xview (Notify_client client
, int fd
)
722 wxSocketBase
*sock
= (wxSocketBase
*)client
;
724 if (!sock
->IsConnected())
725 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
727 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
729 return (Notify_value
) TRUE
;
733 wxSocketBase::wxRequestNotify
wxSocketBase::EventToNotify(wxRequestEvent evt
)
753 void wxSocketBase::SetFlags(wxSockFlags _flags
)
758 unsigned long flag
= 0;
759 ioctl(m_fd
, FIONBIO
, &flag
);
761 // SPEED and WAITALL are antagonists.
762 m_flags
= (wxSockFlags
)(m_flags
& ~WAITALL
);
768 unsigned long flag
= 1;
769 ioctl(m_fd
, FIONBIO
, &flag
);
773 void wxSocketBase::SetNotify(wxRequestNotify flags
)
775 wxRequestNotify old_needed_req
= m_neededreq
;
776 if (flags
& REQ_ACCEPT
)
778 /* Check if server */
779 if (!(GetClassInfo()->IsKindOf(CLASSINFO(wxSocketServer
))))
780 flags
&= ~REQ_ACCEPT
;
785 if (m_cbkon && old_needed_req != flags) seems to be wrong, Robert Roebling
789 if (old_needed_req
!= flags
)
793 void wxSocketBase::SetupCallbacks()
795 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| (m_flags
& SPEED
))
799 #if defined(__WXMOTIF__) || defined(__WXXT__)
800 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
))
802 if (m_internal
->sock_inputid
<= 0)
804 m_internal
->sock_inputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
805 (XtPointer
*) XtInputReadMask
,
806 (XtInputCallbackProc
) wx_socket_read
,
811 if (m_internal
->sock_inputid
> 0)
813 XtRemoveInput(m_internal
->sock_inputid
);
814 m_internal
->sock_inputid
= 0;
818 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
))
820 if (m_internal
->sock_outputid
<= 0)
822 m_internal
->sock_outputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
823 (XtPointer
*) XtInputWriteMask
,
824 (XtInputCallbackProc
) wx_socket_write
,
830 if (m_internal
->sock_outputid
> 0)
832 XtRemoveInput(m_internal
->sock_outputid
);
833 m_internal
->sock_outputid
= 0;
840 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
))
842 if (m_internal
->sock_inputid
<= 0)
844 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_READ
,
845 wx_socket_read
, (gpointer
)this);
850 if (m_internal
->sock_inputid
> 0)
853 gdk_input_remove(m_internal->sock_inputid);
854 m_internal->sock_inputid = 0;
859 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
))
861 if (m_internal
->sock_outputid
<= 0)
863 m_internal
->sock_outputid
= gdk_input_add(m_fd
, GDK_INPUT_WRITE
,
864 wx_socket_write
, (gpointer
)this);
869 if (m_internal
->sock_outputid
> 0)
872 gdk_input_remove(m_internal->sock_outputid);
873 m_internal->sock_outputid = 0;
883 if (m_neededreq
& REQ_READ
)
885 if (m_neededreq
& REQ_WRITE
)
887 if (m_neededreq
& REQ_LOST
)
889 if (m_neededreq
& REQ_ACCEPT
)
891 if (m_neededreq
& REQ_CONNECT
)
894 if (!m_internal
->my_msg
)
895 m_internal
->my_msg
= m_handler
->NewMessage(this);
896 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), m_internal
->my_msg
, mask
);
899 m_processing
= FALSE
;
902 void wxSocketBase::DestroyCallbacks()
904 if (!m_cbkon
|| !m_handler
)
908 m_processing
= FALSE
;
909 #if defined(__WXMOTIF__) || defined(__WXXT__)
910 if (m_internal
->sock_inputid
> 0)
911 XtRemoveInput(m_internal
->sock_inputid
);
912 m_internal
->sock_inputid
= 0;
913 if (m_internal
->sock_outputid
> 0)
914 XtRemoveInput(m_internal
->sock_outputid
);
915 m_internal
->sock_outputid
= 0;
918 if (m_internal
->sock_inputid
> 0)
919 gdk_input_remove(m_internal
->sock_inputid
);
920 m_internal
->sock_inputid
= 0;
921 if (m_internal
->sock_outputid
> 0)
922 gdk_input_remove(m_internal
->sock_outputid
);
923 m_internal
->sock_outputid
= 0;
926 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), 0, 0);
930 void wxSocketBase::Notify(bool notify
)
932 if (m_notifyme
== notify
)
941 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
943 wxRequestNotify req_notif
= EventToNotify(req_evt
);
945 // Mask the current event
946 SetNotify(m_neededreq
& ~req_notif
);
948 if (req_evt
<= EVT_WRITE
&& DoRequests(req_evt
))
951 if (m_waitflags
& 0xF0)
954 if ((m_waitflags
& 0x0F) == req_evt
)
964 if (req_evt
== EVT_LOST
)
970 OldOnNotify(req_evt
);
973 SetNotify(m_neededreq
| req_notif
);
976 wxSocketEvent::wxSocketEvent(int id
)
979 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
984 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
986 wxSocketEvent
event(m_id
);
988 event
.SetEventObject(this);
993 m_cbk(*this, evt
, m_cdata
);
996 // --------------------------------------------------------------
997 // --------- wxSocketBase functions [Callback, CallbackData] ----
998 // --------------------------------------------------------------
1000 wxSocketBase::wxSockCbk
wxSocketBase::Callback(wxSocketBase::wxSockCbk _cbk
)
1002 wxSockCbk old_cbk
= m_cbk
;
1008 char *wxSocketBase::CallbackData(char *cdata_
)
1010 char *old_cdata
= m_cdata
;
1016 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
1018 SetNextHandler(&h_evt
);
1022 // --------------------------------------------------------------
1023 // --------- wxSocketBase pushback library ----------------------
1024 // --------------------------------------------------------------
1026 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
1030 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
1031 curr_pos
= m_unread
+ m_unrd_size
;
1033 memcpy(curr_pos
, buffer
, size
);
1034 m_unrd_size
+= size
;
1037 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
1039 char *curr_pos
, *new_buf
;
1041 new_buf
= (char *) malloc(m_unrd_size
+size
);
1042 curr_pos
= new_buf
+ size
;
1044 memcpy(new_buf
, buffer
, size
);
1045 memcpy(curr_pos
, m_unread
, m_unrd_size
);
1049 m_unrd_size
+= size
;
1052 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
1057 if (size
> m_unrd_size
)
1059 memcpy(buffer
, m_unread
, size
);
1062 m_unrd_size
-= size
;
1072 // --------------------------------------------------------------
1073 // --------- wxSocketBase "multi-thread" core -------------------
1074 // --------------------------------------------------------------
1076 bool wxSocketBase::DoRequests(wxRequestEvent req_flag
)
1078 wxNode
*node
= req_list
[req_flag
].First();
1085 SockRequest
*req
= (SockRequest
*)node
->Data();
1093 ret
= recv(m_fd
, req
->buffer
, req
->size
,
1094 (req
->type
== EVT_PEEK
) ? MSG_PEEK
: 0);
1102 if ((len
< req
->size
) && (m_flags
& WAITALL
))
1107 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1108 req_list
[req_flag
].Insert(req
);
1118 ret
= send(m_fd
, req
->buffer
, req
->size
, 0);
1126 if ((len
< req
->size
) && (m_flags
& WAITALL
))
1131 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1132 req_list
[req_flag
].Insert(req
);
1147 void wxSocketBase::WantSpeedBuffer(char *buffer
, size_t nbytes
,
1156 ret
= recv(m_fd
, buffer
, nbytes
,
1157 (evt
== EVT_PEEK
) ? MSG_PEEK
: 0);
1160 ret
= send(m_fd
, buffer
, nbytes
, 0);
1175 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
1180 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
1183 if (m_flags
& SPEED
)
1185 WantSpeedBuffer(buffer
, nbytes
, evt
);
1189 SockRequest
*buf
= new SockRequest
;
1190 wxSockWakeUp
s_wake(NULL
, (int *)&buf_timed_out
, (int)TRUE
);
1193 req_list
[evt
].Append(buf
);
1196 SetNotify(REQ_LOST
| EventToNotify(evt
));
1198 buf
->buffer
= buffer
;
1203 buf
->auto_wakeup
= &s_wake
;
1205 buf_timed_out
= FALSE
;
1207 s_wake
.Start(m_timeout
*1000, TRUE
);
1208 if (m_flags
& NOWAIT
)
1214 while (!buf
->done
&& !buf_timed_out
)
1218 m_lcount
= buf
->nbytes
;
1220 m_error
= ETIMEDOUT
;
1222 m_error
= buf
->error
;
1228 // --------------------------------------------------------------
1230 // --------------------------------------------------------------
1232 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1233 wxSockFlags flags
) :
1234 wxSocketBase(flags
, SOCK_SERVER
)
1236 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1238 if (m_fd
== INVALID_SOCKET
)
1242 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
1244 struct sockaddr
*myaddr
;
1247 addr_man
.Build(myaddr
, len
);
1248 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
1251 if (listen(m_fd
, 5) < 0) {
1252 m_fd
= INVALID_SOCKET
;
1257 // --------------------------------------------------------------
1258 // wxSocketServer Accept
1259 // --------------------------------------------------------------
1261 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
1265 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
1268 struct linger linger
;
1270 linger
.l_linger
= 1;
1272 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1275 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1277 if (!(sock
.m_flags
& SPEED
))
1279 unsigned long flag2
= 1;
1280 ioctl(fd2
, FIONBIO
, &flag2
);
1283 sock
.m_type
= SOCK_INTERNAL
;
1285 sock
.m_connected
= TRUE
;
1290 wxSocketBase
*wxSocketServer::Accept()
1292 wxSocketBase
* sock
= new wxSocketBase();
1294 sock
->SetFlags((wxSockFlags
)m_flags
);
1296 if (!AcceptWith(*sock
))
1300 m_handler
->Register(sock
);
1305 // --------------------------------------------------------------
1306 // wxSocketServer callbacks
1307 // --------------------------------------------------------------
1309 void wxSocketServer::OnRequest(wxRequestEvent evt
)
1311 if (evt
== EVT_ACCEPT
)
1313 OldOnNotify(EVT_ACCEPT
);
1317 // --------------------------------------------------------------
1319 // --------------------------------------------------------------
1321 // --------- wxSocketClient CONSTRUCTOR -------------------------
1322 // --------------------------------------------------------------
1323 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
1324 wxSocketBase(_flags
, SOCK_CLIENT
)
1328 // --------------------------------------------------------------
1329 // --------- wxSocketClient DESTRUCTOR --------------------------
1330 // --------------------------------------------------------------
1331 wxSocketClient::~wxSocketClient()
1335 // --------------------------------------------------------------
1336 // --------- wxSocketClient Connect functions -------------------
1337 // --------------------------------------------------------------
1338 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
1340 struct linger linger
;
1345 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1350 m_connected
= FALSE
;
1353 linger
.l_linger
= 5;
1354 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1356 // Stay in touch with the state of things...
1358 unsigned long flag
= 1;
1359 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1361 // Disable the nagle algorithm, which delays sends till the
1362 // buffer is full (or a certain time period has passed?)...
1364 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1366 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
1369 struct sockaddr
*remote
;
1372 addr_man
.Build(remote
, len
);
1374 if (connect(m_fd
, remote
, len
) != 0)
1377 if (!(m_flags
& SPEED
))
1380 ioctl(m_fd
, FIONBIO
, &flag
);
1389 bool wxSocketClient::WaitOnConnect(long seconds
, long microseconds
)
1391 int ret
= _Wait(seconds
, microseconds
, REQ_CONNECT
| REQ_LOST
);
1399 void wxSocketClient::OnRequest(wxRequestEvent evt
)
1401 if (evt
== EVT_CONNECT
)
1406 SetNotify(m_neededreq
& ~REQ_CONNECT
);
1412 OldOnNotify(EVT_CONNECT
);
1418 wxSocketBase::OnRequest(evt
);
1421 /////////////////////////////////////////////////////////////////
1422 // wxSocketHandler ///////////////////////////////////////////////
1423 /////////////////////////////////////////////////////////////////
1425 wxSocketHandler
*wxSocketHandler::master
= NULL
;
1426 #if defined(__WINDOWS__)
1427 static int win_initialized
= 0;
1430 // --------------------------------------------------------------
1431 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1432 // --------------------------------------------------------------
1435 extern char wxPanelClassName
[];
1437 LRESULT APIENTRY _EXPORT
wxSocketHandlerWndProc(HWND hWnd
, UINT message
,
1438 WPARAM wParam
, LPARAM lParam
)
1440 if(message
==WM_DESTROY
)
1442 ::SetWindowLong(hWnd
, GWL_WNDPROC
, (LONG
) DefWindowProc
);
1443 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1445 wxSocketHandler
*h_sock
= (wxSocketHandler
*)GetWindowLong(hWnd
, GWL_USERDATA
);
1446 wxNode
*node
= h_sock
->smsg_list
->Find(message
);
1448 wxSocketBase::wxRequestEvent sk_req
;
1449 UINT event
= WSAGETSELECTEVENT(lParam
);
1452 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1454 sock
= (wxSocketBase
*)node
->Data();
1458 sk_req
= wxSocketBase::EVT_READ
;
1461 sk_req
= wxSocketBase::EVT_WRITE
;
1464 sk_req
= wxSocketBase::EVT_LOST
;
1467 sk_req
= wxSocketBase::EVT_ACCEPT
;
1470 sk_req
= wxSocketBase::EVT_CONNECT
;
1473 sock
->OnRequest(sk_req
);
1478 FARPROC wxSocketSubClassProc
= NULL
;
1482 wxSocketHandler::wxSocketHandler()
1484 #if defined(__WINDOWS__)
1485 if (!win_initialized
)
1489 WSAStartup((1 << 8) | 1, &wsaData
);
1490 win_initialized
= 1;
1492 internal
= new wxSockHandlerInternal
;
1493 internal
->sockWin
= ::CreateWindow(wxPanelClassName
, NULL
, 0,
1494 0, 0, 0, 0, NULL
, (HMENU
) NULL
,
1497 // Subclass the window
1498 if (!wxSocketSubClassProc
)
1499 wxSocketSubClassProc
= MakeProcInstance((FARPROC
) wxSocketHandlerWndProc
, wxhInstance
);
1500 ::SetWindowLong(internal
->sockWin
, GWL_WNDPROC
, (LONG
) wxSocketSubClassProc
);
1501 ::SetWindowLong(internal
->sockWin
, GWL_USERDATA
, (LONG
) this);
1503 internal
->firstAvailableMsg
= 5000;
1504 smsg_list
= new wxList(wxKEY_INTEGER
);
1510 signal(SIGPIPE
, SIG_IGN
);
1514 // --------------------------------------------------------------
1515 // --------- wxSocketHandler DESTRUCTOR -------------------------
1516 // --------------------------------------------------------------
1517 wxSocketHandler::~wxSocketHandler()
1519 wxNode
*next_node
, *node
= socks
->First();
1523 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
1526 next_node
= node
->Next();
1536 ::DestroyWindow(internal
->sockWin
);
1538 win_initialized
= 0;
1544 // --------------------------------------------------------------
1545 // --------- wxSocketHandler registering functions --------------
1546 // --------------------------------------------------------------
1548 void wxSocketHandler::Register(wxSocketBase
* sock
)
1552 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next())
1554 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1562 socks
->Append(sock
);
1563 sock
->SetHandler(this);
1564 sock
->SetupCallbacks();
1568 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
1572 for (node
= socks
->First(); node
; node
= node
->Next())
1574 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1579 sock
->DestroyCallbacks();
1580 sock
->SetHandler(NULL
);
1586 unsigned long wxSocketHandler::Count() const
1588 return socks
->Number();
1591 // --------------------------------------------------------------
1592 // --------- wxSocketHandler "big" wait functions ---------------
1593 // --------------------------------------------------------------
1594 void handler_cbk(wxSocketBase
& sock
,
1595 wxSocketBase::wxRequestEvent
WXUNUSED(flags
),
1598 int *a_wait
= (int *)cdata
;
1604 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1608 wxSockWakeUp
s_wake(NULL
, &on_wait
, -2);
1611 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++)
1613 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1617 sock
->SetupCallbacks();
1619 sock
->Callback(handler_cbk
);
1620 sock
->CallbackData((char *)&on_wait
);
1624 s_wake
.Start((seconds
*1000) + (microseconds
/1000), TRUE
);
1629 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++)
1631 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1633 sock
->RestoreState();
1642 void wxSocketHandler::YieldSock()
1646 for (node
= socks
->First(); node
; node
= node
->Next() )
1648 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1652 sock
->SetFlags(wxSocketBase::SPEED
);
1654 sock
->DoRequests(wxSocketBase::EVT_READ
);
1655 sock
->DoRequests(wxSocketBase::EVT_WRITE
);
1657 sock
->RestoreState();
1661 // --------------------------------------------------------------
1662 // --------- wxSocketHandler: create and register the socket ----
1663 // --------------------------------------------------------------
1664 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1665 wxSocketBase::wxSockFlags flags
)
1667 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1673 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1675 wxSocketClient
*client
= new wxSocketClient(flags
);
1682 // --------------------------------------------------------------
1683 // --------- wxSocketHandler: Windows specific methods ----------
1684 // --------------------------------------------------------------
1686 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1688 internal
->firstAvailableMsg
++;
1689 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1690 return internal
->firstAvailableMsg
;
1693 void wxSocketHandler::DestroyMessage(UINT msg
)
1695 wxNode
*node
= smsg_list
->Find(msg
);
1699 HWND
wxSocketHandler::GetHWND() const
1701 return internal
->sockWin
;
1706 bool wxSocketModule::OnInit()
1708 wxSocketHandler::master
= new wxSocketHandler();
1712 void wxSocketModule::OnExit()
1714 delete wxSocketHandler::master
;
1715 wxSocketHandler::master
= NULL
;