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() wxYield()
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(1), 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(1), 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 // --------------------------------------------------------------
267 // --------- wxSocketBase CONSTRUCTOR ---------------------------
268 // --------------------------------------------------------------
269 wxSocketBase::~wxSocketBase()
278 if (m_internal
->my_msg
)
279 m_handler
->DestroyMessage(m_internal
->my_msg
);
281 m_handler
->UnRegister(this);
283 m_states
.DeleteContents(TRUE
);
288 bool wxSocketBase::Close()
290 if (m_fd
!= INVALID_SOCKET
) {
291 for (int i
=0;i
<3;i
++) {
292 wxNode
*n
, *node
= req_list
[i
].First();
295 SockRequest
*req
= (SockRequest
*)node
->Data();
307 m_fd
= INVALID_SOCKET
;
314 // --------------------------------------------------------------
315 // --------- wxSocketBase base IO functions ---------------------
316 // --------------------------------------------------------------
317 wxSocketBase
& wxSocketBase::Read(char* buffer
, size_t nbytes
)
319 m_lcount
= GetPushback(buffer
, nbytes
, FALSE
);
321 // If we have got the whole needed buffer or if we don't want to
322 // wait then it returns immediately.
323 if (!nbytes
|| (m_lcount
&& !(m_flags
& WAITALL
)) )
326 WantBuffer(buffer
, nbytes
, EVT_READ
);
331 wxSocketBase
& wxSocketBase::Peek(char* buffer
, size_t nbytes
)
333 size_t nbytes_old
= nbytes
;
335 nbytes
-= GetPushback(buffer
, nbytes
, TRUE
);
337 m_lcount
= nbytes_old
;
341 WantBuffer(buffer
, nbytes
, EVT_PEEK
);
346 wxSocketBase
& wxSocketBase::Write(const char *buffer
, size_t nbytes
)
348 WantBuffer((char *)buffer
, nbytes
, EVT_WRITE
);
352 wxSocketBase
& wxSocketBase::ReadMsg(char* buffer
, size_t nbytes
)
355 size_t len
, len2
, sig
;
357 Read((char *)&msg
, sizeof(msg
));
358 if (m_lcount
!= sizeof(msg
))
361 sig
= msg
.sig
[0] & 0xff;
362 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
363 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
364 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
366 if (sig
!= 0xfeeddead)
368 len
= msg
.len
[0] & 0xff;
369 len
|= (size_t)(msg
.len
[1] & 0xff) << 8;
370 len
|= (size_t)(msg
.len
[2] & 0xff) << 16;
371 len
|= (size_t)(msg
.len
[3] & 0xff) << 24;
378 if (Read(buffer
, len
).LastCount() != len
)
380 if (len2
&& (Read(NULL
, len2
).LastCount() != len2
))
382 if (Read((char *)&msg
, sizeof(msg
)).LastCount() != sizeof(msg
))
385 sig
= msg
.sig
[0] & 0xff;
386 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
387 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
388 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
390 if (sig
!= 0xdeadfeed)
396 wxSocketBase
& wxSocketBase::WriteMsg(const char *buffer
, size_t nbytes
)
400 msg
.sig
[0] = (char) 0xad;
401 msg
.sig
[1] = (char) 0xde;
402 msg
.sig
[2] = (char) 0xed;
403 msg
.sig
[3] = (char) 0xfe;
405 msg
.len
[0] = (char) nbytes
& 0xff;
406 msg
.len
[1] = (char) (nbytes
>> 8) & 0xff;
407 msg
.len
[2] = (char) (nbytes
>> 16) & 0xff;
408 msg
.len
[3] = (char) (nbytes
>> 24) & 0xff;
410 if (Write((char *)&msg
, sizeof(msg
)).LastCount() < sizeof(msg
))
412 if (Write(buffer
, nbytes
).LastCount() < nbytes
)
415 msg
.sig
[0] = (char) 0xed;
416 msg
.sig
[1] = (char) 0xfe;
417 msg
.sig
[2] = (char) 0xad;
418 msg
.sig
[3] = (char) 0xde;
419 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
420 Write((char *)&msg
, sizeof(msg
));
425 wxSocketBase
& wxSocketBase::Unread(const char *buffer
, size_t nbytes
)
427 CreatePushbackAfter(buffer
, nbytes
);
431 bool wxSocketBase::IsData() const
444 FD_SET(m_fd
, &sock_set
);
445 select(FD_SETSIZE
, &sock_set
, NULL
, NULL
, &tv
);
446 return (FD_ISSET(m_fd
, &sock_set
) != 0);
449 // ---------------------------------------------------------------------
450 // --------- wxSocketBase Discard(): deletes all byte in the input queue
451 // ---------------------------------------------------------------------
452 void wxSocketBase::Discard()
454 #define MAX_BUFSIZE (10*1024)
455 char *my_data
= new char[MAX_BUFSIZE
];
456 size_t recv_size
= MAX_BUFSIZE
;
459 SetFlags((wxSockFlags
)(NOWAIT
| SPEED
));
461 while (recv_size
== MAX_BUFSIZE
) {
462 recv_size
= Read(my_data
, MAX_BUFSIZE
).LastCount();
471 // --------------------------------------------------------------
472 // --------- wxSocketBase socket info functions -----------------
473 // --------------------------------------------------------------
474 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
476 struct sockaddr my_addr
;
477 uint len_addr
= sizeof(my_addr
);
482 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0)
485 addr_man
.Disassemble(&my_addr
, len_addr
);
489 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
491 struct sockaddr my_addr
;
492 uint len_addr
= sizeof(my_addr
);
497 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, &len_addr
) < 0)
501 addr_man
.Disassemble(&my_addr
, len_addr
);
505 // --------------------------------------------------------------
506 // --------- wxSocketBase wait functions ------------------------
507 // --------------------------------------------------------------
509 void wxSocketBase::SaveState()
511 wxSockState
*state
= new wxSockState
;
513 state
->cbk_on
= m_cbkon
;
514 state
->cbk_set
= m_neededreq
;
516 state
->cdata
= m_cdata
;
517 state
->flags
= m_flags
;
518 state
->notif
= m_notifyme
;
520 m_states
.Append(state
);
523 void wxSocketBase::RestoreState()
527 node
= m_states
.Last();
531 wxSockState
*state
= (wxSockState
*)node
->Data();
533 SetFlags(state
->flags
);
534 m_neededreq
= state
->cbk_set
;
536 m_cdata
= state
->cdata
;
537 m_notifyme
= state
->notif
;
547 // --------------------------------------------------------------
548 // --------- wxSocketBase wait functions ------------------------
549 // --------------------------------------------------------------
551 bool wxSocketBase::_Wait(long seconds
, long microseconds
, int type
)
553 if ((!m_connected
&& !m_connecting
) || m_fd
< 0)
556 wxSockWakeUp
wakeup(this, &m_waitflags
, 0);
559 SetNotify((wxRequestNotify
)type
);
563 wakeup
.Start((int)(seconds
*1000 + (microseconds
/ 1000)), TRUE
);
565 m_waitflags
= 0x80 | type
;
566 while (m_waitflags
& 0x80)
571 if (m_waitflags
& 0x40) {
580 bool wxSocketBase::Wait(long seconds
, long microseconds
)
582 return _Wait(seconds
, microseconds
, REQ_ACCEPT
| REQ_CONNECT
|
583 REQ_READ
| REQ_WRITE
| REQ_LOST
);
586 bool wxSocketBase::WaitForRead(long seconds
, long microseconds
)
588 return _Wait(seconds
, microseconds
, REQ_READ
| REQ_LOST
);
591 bool wxSocketBase::WaitForWrite(long seconds
, long microseconds
)
593 return _Wait(seconds
, microseconds
, REQ_WRITE
);
596 bool wxSocketBase::WaitForLost(long seconds
, long microseconds
)
598 return _Wait(seconds
, microseconds
, REQ_LOST
);
601 // --------------------------------------------------------------
602 // --------- wxSocketBase callback management -------------------
603 // --------------------------------------------------------------
605 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
606 #if defined(__WXMOTIF__) || defined(__WXXT__)
607 static void wx_socket_read(XtPointer client
, int *fid
,
608 XtInputId
*WXUNUSED(id
))
611 static void wx_socket_read(gpointer client
, gint fd
,
612 GdkInputCondition
WXUNUSED(cond
))
616 wxSocketBase
*sock
= (wxSocketBase
*)client
;
620 i
= recv(fd
, &c
, 1, MSG_PEEK
);
622 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
)) {
623 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
628 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
631 sock
->OnRequest(wxSocketBase::EVT_READ
);
633 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
)) {
638 sock
->OnRequest(wxSocketBase::EVT_LOST
);
643 #if defined(__WXMOTIF__) || defined(__WXXT__)
644 static void wx_socket_write(XtPointer client
, int *WXUNUSED(fid
),
645 XtInputId
*WXUNUSED(id
))
647 static void wx_socket_write(gpointer client
, gint
WXUNUSED(fd
),
648 GdkInputCondition
WXUNUSED(cond
))
651 wxSocketBase
*sock
= (wxSocketBase
*)client
;
653 if (!sock
->IsConnected())
654 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
656 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
661 Notify_value
wx_sock_read_xview (Notify_client client
, int fd
)
663 wxSocketBase
*sock
= (wxSocketBase
*)client
;
667 i
= recv(fd
, &c
, 1, MSG_PEEK
);
669 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
)) {
670 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
676 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
677 return (Notify_value
) FALSE
;
679 sock
->OnRequest(wxSocketBase::EVT_READ
);
681 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
684 sock
->OnRequest(wxSocketBase::EVT_LOST
);
687 return (Notify_value
) FALSE
;
690 Notify_value
wx_sock_write_xview (Notify_client client
, int fd
)
692 wxSocketBase
*sock
= (wxSocketBase
*)client
;
694 if (!sock
->IsConnected())
695 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
697 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
699 return (Notify_value
) TRUE
;
703 wxSocketBase::wxRequestNotify
wxSocketBase::EventToNotify(wxRequestEvent evt
)
723 void wxSocketBase::SetFlags(wxSockFlags _flags
)
728 unsigned long flag
= 0;
729 ioctl(m_fd
, FIONBIO
, &flag
);
731 // SPEED and WAITALL are antagonists.
732 m_flags
= (wxSockFlags
)(m_flags
& ~WAITALL
);
738 unsigned long flag
= 1;
739 ioctl(m_fd
, FIONBIO
, &flag
);
743 void wxSocketBase::SetNotify(wxRequestNotify flags
)
745 wxRequestNotify old_needed_req
= m_neededreq
;
746 if (flags
& REQ_ACCEPT
)
748 /* Check if server */
749 if (!(GetClassInfo()->IsKindOf(CLASSINFO(wxSocketServer
))))
750 flags
&= ~REQ_ACCEPT
;
755 if (m_cbkon && old_needed_req != flags) seems to be wrong, Robert Roebling
759 if ((!m_cbkon
) || (old_needed_req
!= flags
))
763 void wxSocketBase::SetupCallbacks()
765 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| (m_flags
& SPEED
))
768 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
771 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
)) {
773 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_READ
,
774 wx_socket_read
, (gpointer
)this);
776 m_internal
->sock_inputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
777 (XtPointer
*) XtInputReadMask
,
778 (XtInputCallbackProc
) wx_socket_read
,
782 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
)) {
784 m_internal
->sock_outputid
= gdk_input_add(m_fd
, GDK_INPUT_WRITE
,
785 wx_socket_write
, (gpointer
)this);
787 m_internal
->sock_outputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
788 (XtPointer
*) XtInputWriteMask
,
789 (XtInputCallbackProc
) wx_socket_write
,
797 if (m_neededreq
& REQ_READ
)
799 if (m_neededreq
& REQ_WRITE
)
801 if (m_neededreq
& REQ_LOST
)
803 if (m_neededreq
& REQ_ACCEPT
)
805 if (m_neededreq
& REQ_CONNECT
)
808 if (!m_internal
->my_msg
)
809 m_internal
->my_msg
= m_handler
->NewMessage(this);
810 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), m_internal
->my_msg
, mask
);
813 m_processing
= FALSE
;
816 void wxSocketBase::DestroyCallbacks()
818 if (!m_cbkon
|| !m_handler
)
822 m_processing
= FALSE
;
823 #if defined(__WXMOTIF__) || defined(__WXXT__)
824 if (m_internal
->sock_inputid
> 0)
825 XtRemoveInput(m_internal
->sock_inputid
);
826 m_internal
->sock_inputid
= 0;
827 if (m_internal
->sock_outputid
> 0)
828 XtRemoveInput(m_internal
->sock_outputid
);
829 m_internal
->sock_outputid
= 0;
832 if (m_internal
->sock_inputid
> 0)
833 gdk_input_remove(m_internal
->sock_inputid
);
834 m_internal
->sock_inputid
= 0;
835 if (m_internal
->sock_outputid
> 0)
836 gdk_input_remove(m_internal
->sock_outputid
);
837 m_internal
->sock_outputid
= 0;
840 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), 0, 0);
844 void wxSocketBase::Notify(bool notify
)
846 if (m_notifyme
== notify
)
855 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
857 wxRequestNotify req_notif
= EventToNotify(req_evt
);
859 // Mask the current event
860 SetNotify(m_neededreq
& ~req_notif
);
862 if (req_evt
<= EVT_WRITE
&& DoRequests(req_evt
))
865 if (m_waitflags
& 0xF0)
868 if ((m_waitflags
& 0x0F) == req_evt
)
872 DestroyCallbacks(); // I disable it to prevent infinite loop on X11.
878 if (req_evt
== EVT_LOST
)
884 OldOnNotify(req_evt
);
887 SetNotify(m_neededreq
| req_notif
);
890 wxSocketEvent::wxSocketEvent(int id
)
893 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
898 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
900 wxSocketEvent
event(m_id
);
902 event
.SetEventObject(this);
907 m_cbk(*this, evt
, m_cdata
);
910 // --------------------------------------------------------------
911 // --------- wxSocketBase functions [Callback, CallbackData] ----
912 // --------------------------------------------------------------
914 wxSocketBase::wxSockCbk
wxSocketBase::Callback(wxSocketBase::wxSockCbk _cbk
)
916 wxSockCbk old_cbk
= m_cbk
;
922 char *wxSocketBase::CallbackData(char *cdata_
)
924 char *old_cdata
= m_cdata
;
930 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
932 SetNextHandler(&h_evt
);
936 // --------------------------------------------------------------
937 // --------- wxSocketBase pushback library ----------------------
938 // --------------------------------------------------------------
940 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
944 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
945 curr_pos
= m_unread
+ m_unrd_size
;
947 memcpy(curr_pos
, buffer
, size
);
951 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
953 char *curr_pos
, *new_buf
;
955 new_buf
= (char *) malloc(m_unrd_size
+size
);
956 curr_pos
= new_buf
+ size
;
958 memcpy(new_buf
, buffer
, size
);
959 memcpy(curr_pos
, m_unread
, m_unrd_size
);
966 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
971 if (size
> m_unrd_size
)
973 memcpy(buffer
, m_unread
, size
);
986 // --------------------------------------------------------------
987 // --------- wxSocketBase "multi-thread" core -------------------
988 // --------------------------------------------------------------
990 bool wxSocketBase::DoRequests(wxRequestEvent req_flag
)
992 wxNode
*node
= req_list
[req_flag
].First();
999 SockRequest
*req
= (SockRequest
*)node
->Data();
1007 ret
= recv(m_fd
, req
->buffer
, req
->size
,
1008 (req
->type
== EVT_PEEK
) ? MSG_PEEK
: 0);
1015 if ((len
< req
->size
) && (m_flags
& WAITALL
)) {
1019 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1020 req_list
[req_flag
].Insert(req
);
1030 ret
= send(m_fd
, req
->buffer
, req
->size
, 0);
1037 if ((len
< req
->size
) && (m_flags
& WAITALL
)) {
1041 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1042 req_list
[req_flag
].Insert(req
);
1057 void wxSocketBase::WantSpeedBuffer(char *buffer
, size_t nbytes
,
1065 ret
= recv(m_fd
, buffer
, nbytes
,
1066 (evt
== EVT_PEEK
) ? MSG_PEEK
: 0);
1069 ret
= send(m_fd
, buffer
, nbytes
, 0);
1081 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
1086 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
1089 if (m_flags
& SPEED
) {
1090 WantSpeedBuffer(buffer
, nbytes
, evt
);
1094 SockRequest
*buf
= new SockRequest
;
1095 wxSockWakeUp
s_wake(NULL
, (int *)&buf_timed_out
, (int)TRUE
);
1098 req_list
[evt
].Append(buf
);
1101 SetNotify(REQ_LOST
| EventToNotify(evt
));
1103 buf
->buffer
= buffer
;
1108 buf
->auto_wakeup
= &s_wake
;
1110 buf_timed_out
= FALSE
;
1112 s_wake
.Start(m_timeout
*1000, TRUE
);
1113 if (m_flags
& NOWAIT
)
1119 while (!buf
->done
&& !buf_timed_out
)
1123 m_lcount
= buf
->nbytes
;
1125 m_error
= ETIMEDOUT
;
1127 m_error
= buf
->error
;
1133 // --------------------------------------------------------------
1134 // wxSocketServer ///////////////////////////////////////////////
1135 // --------------------------------------------------------------
1137 // --------------------------------------------------------------
1138 // --------- wxSocketServer CONSTRUCTOR -------------------------
1139 // --------------------------------------------------------------
1140 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1141 wxSockFlags flags
) :
1142 wxSocketBase(flags
, SOCK_SERVER
)
1144 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1146 if (m_fd
== INVALID_SOCKET
)
1150 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
1152 struct sockaddr
*myaddr
;
1155 addr_man
.Build(myaddr
, len
);
1156 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
1159 if (listen(m_fd
, 5) < 0) {
1160 m_fd
= INVALID_SOCKET
;
1165 // --------------------------------------------------------------
1166 // --------- wxSocketServer Accept ------------------------------
1167 // --------------------------------------------------------------
1168 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
1172 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
1175 struct linger linger
;
1177 linger
.l_linger
= 1;
1179 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1182 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1184 if (!(sock
.m_flags
& SPEED
)) {
1185 unsigned long flag2
= 1;
1186 ioctl(fd2
, FIONBIO
, &flag2
);
1189 sock
.m_type
= SOCK_INTERNAL
;
1191 sock
.m_connected
= TRUE
;
1196 wxSocketBase
*wxSocketServer::Accept()
1198 wxSocketBase
* sock
= new wxSocketBase();
1200 sock
->SetFlags((wxSockFlags
)m_flags
);
1202 if (!AcceptWith(*sock
))
1206 m_handler
->Register(sock
);
1211 // --------------------------------------------------------------
1212 // --------- wxSocketServer callbacks ---------------------------
1213 // --------------------------------------------------------------
1214 void wxSocketServer::OnRequest(wxRequestEvent evt
)
1216 if (evt
== EVT_ACCEPT
) {
1217 OldOnNotify(EVT_ACCEPT
);
1221 // --------------------------------------------------------------
1222 // wxSocketClient ///////////////////////////////////////////////
1223 // --------------------------------------------------------------
1225 // --------- wxSocketClient CONSTRUCTOR -------------------------
1226 // --------------------------------------------------------------
1227 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
1228 wxSocketBase(_flags
, SOCK_CLIENT
)
1232 // --------------------------------------------------------------
1233 // --------- wxSocketClient DESTRUCTOR --------------------------
1234 // --------------------------------------------------------------
1235 wxSocketClient::~wxSocketClient()
1239 // --------------------------------------------------------------
1240 // --------- wxSocketClient Connect functions -------------------
1241 // --------------------------------------------------------------
1242 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
1244 struct linger linger
;
1249 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1254 m_connected
= FALSE
;
1257 linger
.l_linger
= 5;
1258 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1260 // Stay in touch with the state of things...
1262 unsigned long flag
= 1;
1263 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1265 // Disable the nagle algorithm, which delays sends till the
1266 // buffer is full (or a certain time period has passed?)...
1268 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1270 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
1273 struct sockaddr
*remote
;
1276 addr_man
.Build(remote
, len
);
1278 if (connect(m_fd
, remote
, len
) != 0)
1281 if (!(m_flags
& SPEED
)) {
1283 ioctl(m_fd
, FIONBIO
, &flag
);
1292 bool wxSocketClient::WaitOnConnect(long seconds
, long microseconds
)
1294 int ret
= _Wait(seconds
, microseconds
, REQ_CONNECT
| REQ_LOST
);
1302 void wxSocketClient::OnRequest(wxRequestEvent evt
)
1304 if (evt
== EVT_CONNECT
) {
1306 SetNotify(m_neededreq
& ~REQ_CONNECT
);
1311 OldOnNotify(EVT_CONNECT
);
1315 wxSocketBase::OnRequest(evt
);
1318 /////////////////////////////////////////////////////////////////
1319 // wxSocketHandler ///////////////////////////////////////////////
1320 /////////////////////////////////////////////////////////////////
1322 wxSocketHandler
*wxSocketHandler::master
= NULL
;
1323 #if defined(__WINDOWS__)
1324 static int win_initialized
= 0;
1327 // --------------------------------------------------------------
1328 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1329 // --------------------------------------------------------------
1332 extern char wxPanelClassName
[];
1334 LRESULT APIENTRY _EXPORT
wxSocketHandlerWndProc(HWND hWnd
, UINT message
,
1335 WPARAM wParam
, LPARAM lParam
)
1337 if(message
==WM_DESTROY
)
1339 ::SetWindowLong(hWnd
, GWL_WNDPROC
, (LONG
) DefWindowProc
);
1340 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1342 wxSocketHandler
*h_sock
= (wxSocketHandler
*)GetWindowLong(hWnd
, GWL_USERDATA
);
1343 wxNode
*node
= h_sock
->smsg_list
->Find(message
);
1345 wxSocketBase::wxRequestEvent sk_req
;
1346 UINT event
= WSAGETSELECTEVENT(lParam
);
1349 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1351 sock
= (wxSocketBase
*)node
->Data();
1355 sk_req
= wxSocketBase::EVT_READ
;
1358 sk_req
= wxSocketBase::EVT_WRITE
;
1361 sk_req
= wxSocketBase::EVT_LOST
;
1364 sk_req
= wxSocketBase::EVT_ACCEPT
;
1367 sk_req
= wxSocketBase::EVT_CONNECT
;
1370 sock
->OnRequest(sk_req
);
1375 FARPROC wxSocketSubClassProc
= NULL
;
1379 wxSocketHandler::wxSocketHandler()
1381 #if defined(__WINDOWS__)
1382 if (!win_initialized
) {
1385 WSAStartup((1 << 8) | 1, &wsaData
);
1386 win_initialized
= 1;
1388 internal
= new wxSockHandlerInternal
;
1389 internal
->sockWin
= ::CreateWindow(wxPanelClassName
, NULL
, 0,
1390 0, 0, 0, 0, NULL
, (HMENU
) NULL
,
1393 // Subclass the window
1394 if (!wxSocketSubClassProc
)
1395 wxSocketSubClassProc
= MakeProcInstance((FARPROC
) wxSocketHandlerWndProc
, wxhInstance
);
1396 ::SetWindowLong(internal
->sockWin
, GWL_WNDPROC
, (LONG
) wxSocketSubClassProc
);
1397 ::SetWindowLong(internal
->sockWin
, GWL_USERDATA
, (LONG
) this);
1399 internal
->firstAvailableMsg
= 5000;
1400 smsg_list
= new wxList(wxKEY_INTEGER
);
1406 signal(SIGPIPE
, SIG_IGN
);
1410 // --------------------------------------------------------------
1411 // --------- wxSocketHandler DESTRUCTOR -------------------------
1412 // --------------------------------------------------------------
1413 wxSocketHandler::~wxSocketHandler()
1415 wxNode
*next_node
, *node
= socks
->First();
1418 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
1421 next_node
= node
->Next();
1431 ::DestroyWindow(internal
->sockWin
);
1433 win_initialized
= 0;
1439 // --------------------------------------------------------------
1440 // --------- wxSocketHandler registering functions --------------
1441 // --------------------------------------------------------------
1442 void wxSocketHandler::Register(wxSocketBase
* sock
)
1446 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next()) {
1447 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1454 socks
->Append(sock
);
1455 sock
->SetHandler(this);
1456 sock
->SetupCallbacks();
1460 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
1464 for (node
= socks
->First(); node
; node
= node
->Next()) {
1465 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1469 sock
->DestroyCallbacks();
1470 sock
->SetHandler(NULL
);
1476 unsigned long wxSocketHandler::Count() const
1478 return socks
->Number();
1481 // --------------------------------------------------------------
1482 // --------- wxSocketHandler "big" wait functions ---------------
1483 // --------------------------------------------------------------
1484 void handler_cbk(wxSocketBase
& sock
,
1485 wxSocketBase::wxRequestEvent
WXUNUSED(flags
),
1488 int *a_wait
= (int *)cdata
;
1494 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1498 wxSockWakeUp
s_wake(NULL
, &on_wait
, -2);
1501 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1502 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1506 sock
->SetupCallbacks();
1508 sock
->Callback(handler_cbk
);
1509 sock
->CallbackData((char *)&on_wait
);
1513 s_wake
.Start((seconds
*1000) + (microseconds
/1000), TRUE
);
1518 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1519 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1521 sock
->RestoreState();
1530 void wxSocketHandler::YieldSock()
1534 for (node
= socks
->First(); node
; node
= node
->Next() ) {
1535 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1539 sock
->SetFlags(wxSocketBase::SPEED
);
1541 sock
->DoRequests(wxSocketBase::EVT_READ
);
1542 sock
->DoRequests(wxSocketBase::EVT_WRITE
);
1544 sock
->RestoreState();
1548 // --------------------------------------------------------------
1549 // --------- wxSocketHandler: create and register the socket ----
1550 // --------------------------------------------------------------
1551 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1552 wxSocketBase::wxSockFlags flags
)
1554 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1560 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1562 wxSocketClient
*client
= new wxSocketClient(flags
);
1569 // --------------------------------------------------------------
1570 // --------- wxSocketHandler: Windows specific methods ----------
1571 // --------------------------------------------------------------
1572 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1574 internal
->firstAvailableMsg
++;
1575 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1576 return internal
->firstAvailableMsg
;
1579 void wxSocketHandler::DestroyMessage(UINT msg
)
1581 wxNode
*node
= smsg_list
->Find(msg
);
1585 HWND
wxSocketHandler::GetHWND() const
1587 return internal
->sockWin
;
1592 bool wxSocketModule::OnInit() {
1593 wxSocketHandler::master
= new wxSocketHandler();
1597 void wxSocketModule::OnExit() {
1598 delete wxSocketHandler::master
;
1599 wxSocketHandler::master
= NULL
;