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
{
161 DECLARE_DYNAMIC_CLASS(wxSocketModule
)
168 // --------------------------------------------------------------
170 // --------------------------------------------------------------
171 #if !USE_SHARED_LIBRARY
172 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
173 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
174 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
175 IMPLEMENT_CLASS(wxSocketHandler
, wxObject
)
176 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
177 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule
, wxModule
)
180 class wxSockWakeUp
: public wxTimer
{
186 wxSockWakeUp(wxSocketBase
*_sock
, int *id
, int new_val
) {
187 my_id
= id
; n_val
= new_val
;
190 virtual void Notify() {
192 if (sock
) sock
->Notify(FALSE
);
197 class SockRequest
: public wxObject
{
203 wxSockWakeUp
*auto_wakeup
;
204 wxSocketBase::wxRequestNotify type
;
208 /////////////////////////////////////////////////////////////////////////////
209 // Some internal define
210 /////////////////////////////////////////////////////////////////////////////
212 // --------------------------------------------------------------
213 // --------- wxSocketBase CONSTRUCTOR ---------------------------
214 // --------------------------------------------------------------
215 wxSocketBase::wxSocketBase(wxSocketBase::wxSockFlags _flags
,
216 wxSocketBase::wxSockType _type
) :
218 m_flags(_flags
), m_type(_type
), m_connected(FALSE
), m_connecting(FALSE
),
219 m_fd(INVALID_SOCKET
), m_waitflags(0), m_cbk(0), m_cdata(0), m_id(-1),
221 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
223 m_unread(NULL
), m_unrd_size(0),
225 m_timeout(3600), m_wantbuf(0)
227 m_internal
= new wxSockInternal
;
228 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
229 m_internal
->sock_inputid
= 0;
230 m_internal
->sock_outputid
= 0;
231 m_internal
->sock_exceptid
= 0;
234 m_internal
->my_msg
= 0;
238 wxSocketBase::wxSocketBase() :
240 m_flags(WAITALL
), m_type(SOCK_UNINIT
), m_connected(FALSE
),
241 m_connecting(FALSE
), m_fd(INVALID_SOCKET
), m_waitflags(0),
242 m_cbk(0), m_cdata(0),
243 m_id(-1), m_handler(0),
244 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
246 m_unread(NULL
), m_unrd_size(0),
248 m_timeout(3600), m_wantbuf(0)
250 m_internal
= new wxSockInternal
;
251 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
252 m_internal
->sock_inputid
= 0;
253 m_internal
->sock_outputid
= 0;
254 m_internal
->sock_exceptid
= 0;
257 m_internal
->my_msg
= 0;
261 // --------------------------------------------------------------
262 // --------- wxSocketBase CONSTRUCTOR ---------------------------
263 // --------------------------------------------------------------
264 wxSocketBase::~wxSocketBase()
273 if (m_internal
->my_msg
)
274 m_handler
->DestroyMessage(m_internal
->my_msg
);
276 m_handler
->UnRegister(this);
278 m_states
.DeleteContents(TRUE
);
283 bool wxSocketBase::Close()
285 if (m_fd
!= INVALID_SOCKET
) {
286 for (int i
=0;i
<3;i
++) {
287 wxNode
*n
, *node
= req_list
[i
].First();
290 SockRequest
*req
= (SockRequest
*)node
->Data();
302 m_fd
= INVALID_SOCKET
;
309 // --------------------------------------------------------------
310 // --------- wxSocketBase base IO functions ---------------------
311 // --------------------------------------------------------------
312 wxSocketBase
& wxSocketBase::Read(char* buffer
, size_t nbytes
)
314 m_lcount
= GetPushback(buffer
, nbytes
, FALSE
);
316 // If we have got the whole needed buffer or if we don't want to
317 // wait then it returns immediately.
318 if (!nbytes
|| (m_lcount
&& !(m_flags
& WAITALL
)) )
321 WantBuffer(buffer
, nbytes
, EVT_READ
);
326 wxSocketBase
& wxSocketBase::Peek(char* buffer
, size_t nbytes
)
328 size_t nbytes_old
= nbytes
;
330 nbytes
-= GetPushback(buffer
, nbytes
, TRUE
);
332 m_lcount
= nbytes_old
;
336 WantBuffer(buffer
, nbytes
, EVT_PEEK
);
341 wxSocketBase
& wxSocketBase::Write(const char *buffer
, size_t nbytes
)
343 WantBuffer((char *)buffer
, nbytes
, EVT_WRITE
);
347 wxSocketBase
& wxSocketBase::ReadMsg(char* buffer
, size_t nbytes
)
350 size_t len
, len2
, sig
;
352 Read((char *)&msg
, sizeof(msg
));
353 if (m_lcount
!= sizeof(msg
))
356 sig
= msg
.sig
[0] & 0xff;
357 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
358 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
359 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
361 if (sig
!= 0xfeeddead)
363 len
= msg
.len
[0] & 0xff;
364 len
|= (size_t)(msg
.len
[1] & 0xff) << 8;
365 len
|= (size_t)(msg
.len
[2] & 0xff) << 16;
366 len
|= (size_t)(msg
.len
[3] & 0xff) << 24;
373 if (Read(buffer
, len
).LastCount() != len
)
375 if (len2
&& (Read(NULL
, len2
).LastCount() != len2
))
377 if (Read((char *)&msg
, sizeof(msg
)).LastCount() != sizeof(msg
))
380 sig
= msg
.sig
[0] & 0xff;
381 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
382 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
383 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
385 if (sig
!= 0xdeadfeed)
391 wxSocketBase
& wxSocketBase::WriteMsg(const char *buffer
, size_t nbytes
)
395 msg
.sig
[0] = (char) 0xad;
396 msg
.sig
[1] = (char) 0xde;
397 msg
.sig
[2] = (char) 0xed;
398 msg
.sig
[3] = (char) 0xfe;
400 msg
.len
[0] = (char) nbytes
& 0xff;
401 msg
.len
[1] = (char) (nbytes
>> 8) & 0xff;
402 msg
.len
[2] = (char) (nbytes
>> 16) & 0xff;
403 msg
.len
[3] = (char) (nbytes
>> 24) & 0xff;
405 if (Write((char *)&msg
, sizeof(msg
)).LastCount() < sizeof(msg
))
407 if (Write(buffer
, nbytes
).LastCount() < nbytes
)
410 msg
.sig
[0] = (char) 0xed;
411 msg
.sig
[1] = (char) 0xfe;
412 msg
.sig
[2] = (char) 0xad;
413 msg
.sig
[3] = (char) 0xde;
414 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
415 Write((char *)&msg
, sizeof(msg
));
420 wxSocketBase
& wxSocketBase::Unread(const char *buffer
, size_t nbytes
)
422 CreatePushbackAfter(buffer
, nbytes
);
426 bool wxSocketBase::IsData() const
439 FD_SET(m_fd
, &sock_set
);
440 select(FD_SETSIZE
, &sock_set
, NULL
, NULL
, &tv
);
441 return (FD_ISSET(m_fd
, &sock_set
) != 0);
444 // ---------------------------------------------------------------------
445 // --------- wxSocketBase Discard(): deletes all byte in the input queue
446 // ---------------------------------------------------------------------
447 void wxSocketBase::Discard()
449 #define MAX_BUFSIZE (10*1024)
450 char *my_data
= new char[MAX_BUFSIZE
];
451 size_t recv_size
= MAX_BUFSIZE
;
454 SetFlags((wxSockFlags
)(NOWAIT
| SPEED
));
456 while (recv_size
== MAX_BUFSIZE
) {
457 recv_size
= Read(my_data
, MAX_BUFSIZE
).LastCount();
466 // --------------------------------------------------------------
467 // --------- wxSocketBase socket info functions -----------------
468 // --------------------------------------------------------------
469 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
471 struct sockaddr my_addr
;
472 size_t len_addr
= sizeof(my_addr
);
477 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, (int *)&len_addr
) < 0)
480 addr_man
.Disassemble(&my_addr
, len_addr
);
484 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
486 struct sockaddr my_addr
;
487 size_t len_addr
= sizeof(my_addr
);
492 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, (int *)&len_addr
) < 0)
495 addr_man
.Disassemble(&my_addr
, len_addr
);
499 // --------------------------------------------------------------
500 // --------- wxSocketBase wait functions ------------------------
501 // --------------------------------------------------------------
502 void wxSocketBase::SaveState()
504 wxSockState
*state
= new wxSockState
;
506 state
->cbk_on
= m_cbkon
;
507 state
->cbk_set
= m_neededreq
;
509 state
->cdata
= m_cdata
;
510 state
->flags
= m_flags
;
511 state
->notif
= m_notifyme
;
513 m_states
.Append(state
);
516 void wxSocketBase::RestoreState()
520 node
= m_states
.Last();
524 wxSockState
*state
= (wxSockState
*)node
->Data();
526 SetFlags(state
->flags
);
527 m_neededreq
= state
->cbk_set
;
529 m_cdata
= state
->cdata
;
530 m_notifyme
= state
->notif
;
540 // --------------------------------------------------------------
541 // --------- wxSocketBase wait functions ------------------------
542 // --------------------------------------------------------------
544 bool wxSocketBase::_Wait(long seconds
, long microseconds
, int type
)
546 if ((!m_connected
&& !m_connecting
) || m_fd
< 0)
549 wxSockWakeUp
wakeup(this, &m_waitflags
, 0);
552 SetNotify((wxRequestNotify
)type
);
556 wakeup
.Start((int)(seconds
*1000 + (microseconds
/ 1000)), TRUE
);
558 m_waitflags
= 0x80 | type
;
559 while (m_waitflags
& 0x80)
564 if (m_waitflags
& 0x40) {
573 bool wxSocketBase::Wait(long seconds
, long microseconds
)
575 return _Wait(seconds
, microseconds
, REQ_ACCEPT
| REQ_CONNECT
|
576 REQ_READ
| REQ_WRITE
| REQ_LOST
);
579 bool wxSocketBase::WaitForRead(long seconds
, long microseconds
)
581 return _Wait(seconds
, microseconds
, REQ_READ
| REQ_LOST
);
584 bool wxSocketBase::WaitForWrite(long seconds
, long microseconds
)
586 return _Wait(seconds
, microseconds
, REQ_WRITE
);
589 bool wxSocketBase::WaitForLost(long seconds
, long microseconds
)
591 return _Wait(seconds
, microseconds
, REQ_LOST
);
594 // --------------------------------------------------------------
595 // --------- wxSocketBase callback management -------------------
596 // --------------------------------------------------------------
598 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
599 #if defined(__WXMOTIF__) || defined(__WXXT__)
600 static void wx_socket_read(XtPointer client
, int *fid
,
601 XtInputId
*WXUNUSED(id
))
604 static void wx_socket_read(gpointer client
, gint fd
,
605 GdkInputCondition
WXUNUSED(cond
))
609 wxSocketBase
*sock
= (wxSocketBase
*)client
;
613 i
= recv(fd
, &c
, 1, MSG_PEEK
);
615 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
)) {
616 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
621 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
624 sock
->OnRequest(wxSocketBase::EVT_READ
);
626 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
)) {
631 sock
->OnRequest(wxSocketBase::EVT_LOST
);
636 #if defined(__WXMOTIF__) || defined(__WXXT__)
637 static void wx_socket_write(XtPointer client
, int *WXUNUSED(fid
),
638 XtInputId
*WXUNUSED(id
))
640 static void wx_socket_write(gpointer client
, gint
WXUNUSED(fd
),
641 GdkInputCondition
WXUNUSED(cond
))
644 wxSocketBase
*sock
= (wxSocketBase
*)client
;
646 if (!sock
->IsConnected())
647 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
649 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
654 Notify_value
wx_sock_read_xview (Notify_client client
, int fd
)
656 wxSocketBase
*sock
= (wxSocketBase
*)client
;
660 i
= recv(fd
, &c
, 1, MSG_PEEK
);
662 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
)) {
663 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
669 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
670 return (Notify_value
) FALSE
;
672 sock
->OnRequest(wxSocketBase::EVT_READ
);
674 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
677 sock
->OnRequest(wxSocketBase::EVT_LOST
);
680 return (Notify_value
) FALSE
;
683 Notify_value
wx_sock_write_xview (Notify_client client
, int fd
)
685 wxSocketBase
*sock
= (wxSocketBase
*)client
;
687 if (!sock
->IsConnected())
688 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
690 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
692 return (Notify_value
) TRUE
;
696 wxSocketBase::wxRequestNotify
wxSocketBase::EventToNotify(wxRequestEvent evt
)
715 void wxSocketBase::SetFlags(wxSockFlags _flags
)
718 if (_flags
& SPEED
) {
719 unsigned long flag
= 0;
720 ioctl(m_fd
, FIONBIO
, &flag
);
722 // SPEED and WAITALL are antagonists.
723 m_flags
= (wxSockFlags
)(m_flags
& ~WAITALL
);
727 unsigned long flag
= 1;
728 ioctl(m_fd
, FIONBIO
, &flag
);
732 void wxSocketBase::SetNotify(wxRequestNotify flags
)
734 wxRequestNotify old_needed_req
= m_neededreq
;
735 if (flags
& REQ_ACCEPT
) {
736 /* Check if server */
737 if (!(GetClassInfo()->IsKindOf(CLASSINFO(wxSocketServer
))))
738 flags
&= ~REQ_ACCEPT
;
741 if (m_cbkon
&& old_needed_req
!= flags
)
745 void wxSocketBase::SetupCallbacks()
747 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| (m_flags
& SPEED
))
750 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
753 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
)) {
755 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_READ
,
756 wx_socket_read
, (gpointer
)this);
758 m_internal
->sock_inputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
759 (XtPointer
*) XtInputReadMask
,
760 (XtInputCallbackProc
) wx_socket_read
,
764 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
)) {
766 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_WRITE
,
767 wx_socket_write
, (gpointer
)this);
769 m_internal
->sock_outputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
770 (XtPointer
*) XtInputWriteMask
,
771 (XtInputCallbackProc
) wx_socket_write
,
779 if (m_neededreq
& REQ_READ
)
781 if (m_neededreq
& REQ_WRITE
)
783 if (m_neededreq
& REQ_LOST
)
785 if (m_neededreq
& REQ_ACCEPT
)
787 if (m_neededreq
& REQ_CONNECT
)
790 if (!m_internal
->my_msg
)
791 m_internal
->my_msg
= m_handler
->NewMessage(this);
792 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), m_internal
->my_msg
, mask
);
795 m_processing
= FALSE
;
798 void wxSocketBase::DestroyCallbacks()
800 if (!m_cbkon
|| !m_handler
)
803 m_processing
= FALSE
;
804 #if defined(__WXMOTIF__) || defined(__WXXT__)
805 if (m_internal
->sock_inputid
> 0)
806 XtRemoveInput(m_internal
->sock_inputid
);
807 m_internal
->sock_inputid
= 0;
808 if (m_internal
->sock_outputid
> 0)
809 XtRemoveInput(m_internal
->sock_outputid
);
810 m_internal
->sock_outputid
= 0;
813 if (m_internal
->sock_inputid
> 0)
814 gdk_input_remove(m_internal
->sock_inputid
);
815 m_internal
->sock_inputid
= 0;
816 if (m_internal
->sock_outputid
> 0)
817 gdk_input_remove(m_internal
->sock_outputid
);
818 m_internal
->sock_outputid
= 0;
821 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), 0, 0);
825 void wxSocketBase::Notify(bool notify
)
827 if (m_notifyme
== notify
)
836 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
838 wxRequestNotify req_notif
= EventToNotify(req_evt
);
840 // Mask the current event
841 SetNotify(m_neededreq
& ~req_notif
);
843 if (req_evt
<= EVT_WRITE
&& DoRequests(req_evt
))
846 if (m_waitflags
& 0xF0) {
848 if ((m_waitflags
& 0x0F) == req_evt
) {
851 DestroyCallbacks(); // I disable it to prevent infinite loop on X11.
857 if (req_evt
== EVT_LOST
) {
862 OldOnNotify(req_evt
);
865 SetNotify(m_neededreq
| req_notif
);
868 wxSocketEvent::wxSocketEvent(int id
)
871 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
876 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
878 wxSocketEvent
event(m_id
);
880 event
.SetEventObject(this);
885 m_cbk(*this, evt
, m_cdata
);
888 // --------------------------------------------------------------
889 // --------- wxSocketBase functions [Callback, CallbackData] ----
890 // --------------------------------------------------------------
891 wxSocketBase::wxSockCbk
wxSocketBase::Callback(wxSocketBase::wxSockCbk _cbk
)
893 wxSockCbk old_cbk
= m_cbk
;
899 char *wxSocketBase::CallbackData(char *cdata_
)
901 char *old_cdata
= m_cdata
;
907 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
909 SetNextHandler(&h_evt
);
913 // --------------------------------------------------------------
914 // --------- wxSocketBase pushback library ----------------------
915 // --------------------------------------------------------------
916 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
920 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
921 curr_pos
= m_unread
+ m_unrd_size
;
923 memcpy(curr_pos
, buffer
, size
);
927 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
929 char *curr_pos
, *new_buf
;
931 new_buf
= (char *) malloc(m_unrd_size
+size
);
932 curr_pos
= new_buf
+ size
;
934 memcpy(new_buf
, buffer
, size
);
935 memcpy(curr_pos
, m_unread
, m_unrd_size
);
942 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
947 if (size
> m_unrd_size
)
949 memcpy(buffer
, m_unread
, size
);
962 // --------------------------------------------------------------
963 // --------- wxSocketBase "multi-thread" core -------------------
964 // --------------------------------------------------------------
966 bool wxSocketBase::DoRequests(wxRequestEvent req_flag
)
968 wxNode
*node
= req_list
[req_flag
].First();
975 SockRequest
*req
= (SockRequest
*)node
->Data();
982 ret
= recv(m_fd
, req
->buffer
, req
->size
,
983 (req
->type
== EVT_PEEK
) ? MSG_PEEK
: 0);
990 if ((len
< req
->size
) && (m_flags
& WAITALL
)) {
994 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
995 req_list
[req_flag
].Insert(req
);
1005 ret
= send(m_fd
, req
->buffer
, req
->size
, 0);
1012 if ((len
< req
->size
) && (m_flags
& WAITALL
)) {
1016 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1017 req_list
[req_flag
].Insert(req
);
1032 void wxSocketBase::WantSpeedBuffer(char *buffer
, size_t nbytes
,
1040 ret
= recv(m_fd
, buffer
, nbytes
,
1041 (evt
== EVT_PEEK
) ? MSG_PEEK
: 0);
1044 ret
= send(m_fd
, buffer
, nbytes
, 0);
1056 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
1061 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
1064 if (m_flags
& SPEED
) {
1065 WantSpeedBuffer(buffer
, nbytes
, evt
);
1069 SockRequest
*buf
= new SockRequest
;
1070 wxSockWakeUp
s_wake(NULL
, (int *)&buf_timed_out
, (int)TRUE
);
1073 req_list
[evt
].Append(buf
);
1076 SetNotify(REQ_LOST
| EventToNotify(evt
));
1078 buf
->buffer
= buffer
;
1083 buf
->auto_wakeup
= &s_wake
;
1085 buf_timed_out
= FALSE
;
1087 s_wake
.Start(m_timeout
*1000, TRUE
);
1088 if (m_flags
& NOWAIT
) {
1091 while (!buf
->done
&& !buf_timed_out
)
1095 m_lcount
= buf
->nbytes
;
1097 m_error
= ETIMEDOUT
;
1099 m_error
= buf
->error
;
1105 // --------------------------------------------------------------
1106 // wxSocketServer ///////////////////////////////////////////////
1107 // --------------------------------------------------------------
1109 // --------------------------------------------------------------
1110 // --------- wxSocketServer CONSTRUCTOR -------------------------
1111 // --------------------------------------------------------------
1112 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1113 wxSockFlags flags
) :
1114 wxSocketBase(flags
, SOCK_SERVER
)
1116 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1118 if (m_fd
== INVALID_SOCKET
)
1122 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
1124 struct sockaddr
*myaddr
;
1127 addr_man
.Build(myaddr
, len
);
1128 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
1131 if (listen(m_fd
, 5) < 0) {
1132 m_fd
= INVALID_SOCKET
;
1137 // --------------------------------------------------------------
1138 // --------- wxSocketServer Accept ------------------------------
1139 // --------------------------------------------------------------
1140 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
1144 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
1147 struct linger linger
;
1149 linger
.l_linger
= 1;
1151 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1154 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1156 if (!(sock
.m_flags
& SPEED
)) {
1157 unsigned long flag2
= 1;
1158 ioctl(fd2
, FIONBIO
, &flag2
);
1161 sock
.m_type
= SOCK_INTERNAL
;
1163 sock
.m_connected
= TRUE
;
1168 wxSocketBase
*wxSocketServer::Accept()
1170 wxSocketBase
* sock
= new wxSocketBase();
1172 sock
->SetFlags((wxSockFlags
)m_flags
);
1174 if (!AcceptWith(*sock
))
1178 m_handler
->Register(sock
);
1183 // --------------------------------------------------------------
1184 // --------- wxSocketServer callbacks ---------------------------
1185 // --------------------------------------------------------------
1186 void wxSocketServer::OnRequest(wxRequestEvent evt
)
1188 if (evt
== EVT_ACCEPT
) {
1189 OldOnNotify(EVT_ACCEPT
);
1193 // --------------------------------------------------------------
1194 // wxSocketClient ///////////////////////////////////////////////
1195 // --------------------------------------------------------------
1197 // --------- wxSocketClient CONSTRUCTOR -------------------------
1198 // --------------------------------------------------------------
1199 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
1200 wxSocketBase(_flags
, SOCK_CLIENT
)
1204 // --------------------------------------------------------------
1205 // --------- wxSocketClient DESTRUCTOR --------------------------
1206 // --------------------------------------------------------------
1207 wxSocketClient::~wxSocketClient()
1211 // --------------------------------------------------------------
1212 // --------- wxSocketClient Connect functions -------------------
1213 // --------------------------------------------------------------
1214 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
1216 struct linger linger
;
1221 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1226 m_connected
= FALSE
;
1229 linger
.l_linger
= 5;
1230 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1232 // Stay in touch with the state of things...
1234 unsigned long flag
= 1;
1235 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1237 // Disable the nagle algorithm, which delays sends till the
1238 // buffer is full (or a certain time period has passed?)...
1240 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1242 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
1245 struct sockaddr
*remote
;
1248 addr_man
.Build(remote
, len
);
1250 if (connect(m_fd
, remote
, len
) != 0)
1253 if (!(m_flags
& SPEED
)) {
1255 ioctl(m_fd
, FIONBIO
, &flag
);
1264 bool wxSocketClient::WaitOnConnect(long seconds
, long microseconds
)
1266 int ret
= _Wait(seconds
, microseconds
, REQ_CONNECT
| REQ_LOST
);
1274 void wxSocketClient::OnRequest(wxRequestEvent evt
)
1276 if (evt
== EVT_CONNECT
) {
1278 SetNotify(m_neededreq
& ~REQ_CONNECT
);
1283 OldOnNotify(EVT_CONNECT
);
1287 wxSocketBase::OnRequest(evt
);
1290 /////////////////////////////////////////////////////////////////
1291 // wxSocketHandler ///////////////////////////////////////////////
1292 /////////////////////////////////////////////////////////////////
1294 wxSocketHandler
*wxSocketHandler::master
= NULL
;
1295 #if defined(__WINDOWS__)
1296 static int win_initialized
= 0;
1299 // --------------------------------------------------------------
1300 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1301 // --------------------------------------------------------------
1304 extern char wxPanelClassName
[];
1306 LRESULT APIENTRY _EXPORT
wxSocketHandlerWndProc(HWND hWnd
, UINT message
,
1307 WPARAM wParam
, LPARAM lParam
)
1309 if(message
==WM_DESTROY
)
1311 ::SetWindowLong(hWnd
, GWL_WNDPROC
, (LONG
) DefWindowProc
);
1312 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1314 wxSocketHandler
*h_sock
= (wxSocketHandler
*)GetWindowLong(hWnd
, GWL_USERDATA
);
1315 wxNode
*node
= h_sock
->smsg_list
->Find(message
);
1317 wxSocketBase::wxRequestEvent sk_req
;
1318 UINT event
= WSAGETSELECTEVENT(lParam
);
1321 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1323 sock
= (wxSocketBase
*)node
->Data();
1327 sk_req
= wxSocketBase::EVT_READ
;
1330 sk_req
= wxSocketBase::EVT_WRITE
;
1333 sk_req
= wxSocketBase::EVT_LOST
;
1336 sk_req
= wxSocketBase::EVT_ACCEPT
;
1339 sk_req
= wxSocketBase::EVT_CONNECT
;
1342 sock
->OnRequest(sk_req
);
1347 FARPROC wxSocketSubClassProc
= NULL
;
1351 wxSocketHandler::wxSocketHandler()
1353 #if defined(__WINDOWS__)
1354 if (!win_initialized
) {
1357 WSAStartup((1 << 8) | 1, &wsaData
);
1358 win_initialized
= 1;
1360 internal
= new wxSockHandlerInternal
;
1361 internal
->sockWin
= ::CreateWindow(wxPanelClassName
, NULL
, 0,
1362 0, 0, 0, 0, NULL
, (HMENU
) NULL
,
1365 // Subclass the window
1366 if (!wxSocketSubClassProc
)
1367 wxSocketSubClassProc
= MakeProcInstance((FARPROC
) wxSocketHandlerWndProc
, wxhInstance
);
1368 ::SetWindowLong(internal
->sockWin
, GWL_WNDPROC
, (LONG
) wxSocketSubClassProc
);
1369 ::SetWindowLong(internal
->sockWin
, GWL_USERDATA
, (LONG
) this);
1371 internal
->firstAvailableMsg
= 5000;
1372 smsg_list
= new wxList(wxKEY_INTEGER
);
1378 signal(SIGPIPE
, SIG_IGN
);
1382 // --------------------------------------------------------------
1383 // --------- wxSocketHandler DESTRUCTOR -------------------------
1384 // --------------------------------------------------------------
1385 wxSocketHandler::~wxSocketHandler()
1387 wxNode
*next_node
, *node
= socks
->First();
1390 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
1393 next_node
= node
->Next();
1403 ::DestroyWindow(internal
->sockWin
);
1405 win_initialized
= 0;
1411 // --------------------------------------------------------------
1412 // --------- wxSocketHandler registering functions --------------
1413 // --------------------------------------------------------------
1414 void wxSocketHandler::Register(wxSocketBase
* sock
)
1418 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next()) {
1419 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1426 socks
->Append(sock
);
1427 sock
->SetHandler(this);
1428 sock
->SetupCallbacks();
1432 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
1436 for (node
= socks
->First(); node
; node
= node
->Next()) {
1437 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1441 sock
->DestroyCallbacks();
1442 sock
->SetHandler(NULL
);
1448 unsigned long wxSocketHandler::Count() const
1450 return socks
->Number();
1453 // --------------------------------------------------------------
1454 // --------- wxSocketHandler "big" wait functions ---------------
1455 // --------------------------------------------------------------
1456 void handler_cbk(wxSocketBase
& sock
,
1457 wxSocketBase::wxRequestEvent
WXUNUSED(flags
),
1460 int *a_wait
= (int *)cdata
;
1466 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1470 wxSockWakeUp
s_wake(NULL
, &on_wait
, -2);
1473 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1474 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1478 sock
->SetupCallbacks();
1480 sock
->Callback(handler_cbk
);
1481 sock
->CallbackData((char *)&on_wait
);
1485 s_wake
.Start((seconds
*1000) + (microseconds
/1000), TRUE
);
1490 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1491 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1493 sock
->RestoreState();
1502 void wxSocketHandler::YieldSock()
1506 for (node
= socks
->First(); node
; node
= node
->Next() ) {
1507 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1511 sock
->SetFlags(wxSocketBase::SPEED
);
1513 sock
->DoRequests(wxSocketBase::EVT_READ
);
1514 sock
->DoRequests(wxSocketBase::EVT_WRITE
);
1516 sock
->RestoreState();
1520 // --------------------------------------------------------------
1521 // --------- wxSocketHandler: create and register the socket ----
1522 // --------------------------------------------------------------
1523 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1524 wxSocketBase::wxSockFlags flags
)
1526 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1532 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1534 wxSocketClient
*client
= new wxSocketClient(flags
);
1541 // --------------------------------------------------------------
1542 // --------- wxSocketHandler: Windows specific methods ----------
1543 // --------------------------------------------------------------
1544 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1546 internal
->firstAvailableMsg
++;
1547 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1548 return internal
->firstAvailableMsg
;
1551 void wxSocketHandler::DestroyMessage(UINT msg
)
1553 wxNode
*node
= smsg_list
->Find(msg
);
1557 HWND
wxSocketHandler::GetHWND() const
1559 return internal
->sockWin
;
1564 bool wxSocketModule::OnInit() {
1565 wxSocketHandler::master
= new wxSocketHandler();
1569 void wxSocketModule::OnExit() {
1570 delete wxSocketHandler::master
;
1571 wxSocketHandler::master
= NULL
;