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>
38 /////////////////////////////////////////////////////////////////////////////
39 // System specific headers
40 /////////////////////////////////////////////////////////////////////////////
41 #if defined(__WINDOWS__)
50 #include <sys/socket.h>
52 #include <sys/ioctl.h>
58 #include <sys/filio.h>
70 #if defined(__WXMOTIF__) || defined(__WXXT__)
71 #include <X11/Intrinsic.h>
73 /////////////////////////////
74 // Needs internal variables
75 /////////////////////////////
77 #define Uses_XtIntrinsic
82 #if defined(__WXGTK__)
86 /////////////////////////////////////////////////////////////////////////////
88 /////////////////////////////////////////////////////////////////////////////
89 #define WXSOCK_INTERNAL
90 #include "wx/sckaddr.h"
91 #include "wx/socket.h"
93 /////////////////////////////////////////////////////////////////////////////
94 // Some patch ///// BEGIN
95 /////////////////////////////////////////////////////////////////////////////
97 #define close closesocket
98 #define ioctl ioctlsocket
102 #define errno WSAGetLastError()
106 #define EWOULDBLOCK WSAEWOULDBLOCK
107 #define ETIMEDOUT WSAETIMEDOUT
109 #define EINTR WSAEINTR
113 #define INVALID_SOCKET -1
117 #define wxAPP_CONTEXT wxTheApp->appContext
121 // This is an MS TCP/IP routine and is not needed here. Some WinSock
122 // implementations (such as PC-NFS) will require you to include this
123 // or a similar routine (see appendix in WinSock doc or help file).
125 #if defined( NEED_WSAFDIsSet ) || defined( _MSC_VER )
126 int PASCAL FAR
__WSAFDIsSet(SOCKET fd
, fd_set FAR
*set
)
128 int i
= set
->fd_count
;
132 if (set
->fd_array
[i
] == fd
)
141 #if defined(__WINDOWS__)
142 #define PROCESS_EVENTS() wxYield()
143 #elif defined(__WXXT__) || defined(__WXMOTIF__)
144 #define PROCESS_EVENTS() XtAppProcessEvent(wxAPP_CONTEXT, XtIMAll)
145 #elif defined(__WXGTK__)
146 #define PROCESS_EVENTS() gtk_main_iteration()
149 /////////////////////////////////////////////////////////////////////////////
150 // Some patch ///// END
151 /////////////////////////////////////////////////////////////////////////////
153 // --------------------------------------------------------------
155 // --------------------------------------------------------------
156 #if !USE_SHARED_LIBRARY
157 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
158 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
159 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
160 IMPLEMENT_CLASS(wxSocketHandler
, wxObject
)
161 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
164 class wxSockWakeUp
: public wxTimer
{
170 wxSockWakeUp(wxSocketBase
*_sock
, int *id
, int new_val
) {
171 my_id
= id
; n_val
= new_val
;
174 virtual void Notify() {
176 if (sock
) sock
->Notify(FALSE
);
181 class SockRequest
: public wxObject
{
187 wxSockWakeUp
*auto_wakeup
;
188 wxSocketBase::wxRequestNotify type
;
192 /////////////////////////////////////////////////////////////////////////////
193 // Some internal define
194 /////////////////////////////////////////////////////////////////////////////
196 // --------------------------------------------------------------
197 // --------- wxSocketBase CONSTRUCTOR ---------------------------
198 // --------------------------------------------------------------
199 wxSocketBase::wxSocketBase(wxSocketBase::wxSockFlags _flags
,
200 wxSocketBase::wxSockType _type
) :
202 m_flags(_flags
), m_type(_type
), m_connected(FALSE
), m_connecting(FALSE
),
203 m_fd(INVALID_SOCKET
), m_waitflags(0), m_cbk(0), m_cdata(0), m_id(-1),
205 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
207 m_unread(NULL
), m_unrd_size(0),
209 m_timeout(3600), m_wantbuf(0)
211 m_internal
= new wxSockInternal
;
212 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
213 m_internal
->sock_inputid
= 0;
214 m_internal
->sock_outputid
= 0;
215 m_internal
->sock_exceptid
= 0;
218 m_internal
->my_msg
= 0;
222 wxSocketBase::wxSocketBase() :
224 m_flags(WAITALL
), m_type(SOCK_UNINIT
), m_connected(FALSE
),
225 m_connecting(FALSE
), m_fd(INVALID_SOCKET
), m_waitflags(0),
226 m_cbk(0), m_cdata(0),
227 m_id(-1), m_handler(0),
228 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
230 m_unread(NULL
), m_unrd_size(0),
232 m_timeout(3600), m_wantbuf(0)
234 m_internal
= new wxSockInternal
;
235 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
236 m_internal
->sock_inputid
= 0;
237 m_internal
->sock_outputid
= 0;
238 m_internal
->sock_exceptid
= 0;
241 m_internal
->my_msg
= 0;
245 // --------------------------------------------------------------
246 // --------- wxSocketBase CONSTRUCTOR ---------------------------
247 // --------------------------------------------------------------
248 wxSocketBase::~wxSocketBase()
257 if (m_internal
->my_msg
)
258 m_handler
->DestroyMessage(m_internal
->my_msg
);
260 m_handler
->UnRegister(this);
262 m_states
.DeleteContents(TRUE
);
267 bool wxSocketBase::Close()
269 if (m_fd
!= INVALID_SOCKET
) {
270 for (int i
=0;i
<3;i
++) {
271 wxNode
*n
, *node
= req_list
[i
].First();
274 SockRequest
*req
= (SockRequest
*)node
->Data();
286 m_fd
= INVALID_SOCKET
;
293 // --------------------------------------------------------------
294 // --------- wxSocketBase base IO functions ---------------------
295 // --------------------------------------------------------------
296 wxSocketBase
& wxSocketBase::Read(char* buffer
, size_t nbytes
)
298 m_lcount
= GetPushback(buffer
, nbytes
, FALSE
);
300 // If we have got the whole needed buffer or if we don't want to
301 // wait then it returns immediately.
302 if (!nbytes
|| (m_lcount
&& !(m_flags
& WAITALL
)) )
305 WantBuffer(buffer
, nbytes
, EVT_READ
);
310 wxSocketBase
& wxSocketBase::Peek(char* buffer
, size_t nbytes
)
312 size_t nbytes_old
= nbytes
;
314 nbytes
-= GetPushback(buffer
, nbytes
, TRUE
);
316 m_lcount
= nbytes_old
;
320 WantBuffer(buffer
, nbytes
, EVT_PEEK
);
325 wxSocketBase
& wxSocketBase::Write(const char *buffer
, size_t nbytes
)
327 WantBuffer((char *)buffer
, nbytes
, EVT_WRITE
);
331 wxSocketBase
& wxSocketBase::ReadMsg(char* buffer
, size_t nbytes
)
334 size_t len
, len2
, sig
;
336 Read((char *)&msg
, sizeof(msg
));
337 if (m_lcount
!= sizeof(msg
))
340 sig
= msg
.sig
[0] & 0xff;
341 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
342 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
343 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
345 if (sig
!= 0xfeeddead)
347 len
= msg
.len
[0] & 0xff;
348 len
|= (size_t)(msg
.len
[1] & 0xff) << 8;
349 len
|= (size_t)(msg
.len
[2] & 0xff) << 16;
350 len
|= (size_t)(msg
.len
[3] & 0xff) << 24;
357 if (Read(buffer
, len
).LastCount() != len
)
359 if (len2
&& (Read(NULL
, len2
).LastCount() != len2
))
361 if (Read((char *)&msg
, sizeof(msg
)).LastCount() != sizeof(msg
))
364 sig
= msg
.sig
[0] & 0xff;
365 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
366 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
367 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
369 if (sig
!= 0xdeadfeed)
375 wxSocketBase
& wxSocketBase::WriteMsg(const char *buffer
, size_t nbytes
)
379 msg
.sig
[0] = (char) 0xad;
380 msg
.sig
[1] = (char) 0xde;
381 msg
.sig
[2] = (char) 0xed;
382 msg
.sig
[3] = (char) 0xfe;
384 msg
.len
[0] = (char) nbytes
& 0xff;
385 msg
.len
[1] = (char) (nbytes
>> 8) & 0xff;
386 msg
.len
[2] = (char) (nbytes
>> 16) & 0xff;
387 msg
.len
[3] = (char) (nbytes
>> 24) & 0xff;
389 if (Write((char *)&msg
, sizeof(msg
)).LastCount() < sizeof(msg
))
391 if (Write(buffer
, nbytes
).LastCount() < nbytes
)
394 msg
.sig
[0] = (char) 0xed;
395 msg
.sig
[1] = (char) 0xfe;
396 msg
.sig
[2] = (char) 0xad;
397 msg
.sig
[3] = (char) 0xde;
398 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
399 Write((char *)&msg
, sizeof(msg
));
404 wxSocketBase
& wxSocketBase::Unread(const char *buffer
, size_t nbytes
)
406 CreatePushbackAfter(buffer
, nbytes
);
410 bool wxSocketBase::IsData() const
423 FD_SET(m_fd
, &sock_set
);
424 select(FD_SETSIZE
, &sock_set
, NULL
, NULL
, &tv
);
425 return (FD_ISSET(m_fd
, &sock_set
) != 0);
428 // ---------------------------------------------------------------------
429 // --------- wxSocketBase Discard(): deletes all byte in the input queue
430 // ---------------------------------------------------------------------
431 void wxSocketBase::Discard()
433 #define MAX_BUFSIZE (10*1024)
434 char *my_data
= new char[MAX_BUFSIZE
];
435 size_t recv_size
= MAX_BUFSIZE
;
438 SetFlags((wxSockFlags
)(NOWAIT
| SPEED
));
440 while (recv_size
== MAX_BUFSIZE
) {
441 recv_size
= Read(my_data
, MAX_BUFSIZE
).LastCount();
450 // --------------------------------------------------------------
451 // --------- wxSocketBase socket info functions -----------------
452 // --------------------------------------------------------------
453 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
455 struct sockaddr my_addr
;
456 size_t len_addr
= sizeof(my_addr
);
461 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, (int *)&len_addr
) < 0)
464 addr_man
.Disassemble(&my_addr
, len_addr
);
468 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
470 struct sockaddr my_addr
;
471 size_t len_addr
= sizeof(my_addr
);
476 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, (int *)&len_addr
) < 0)
479 addr_man
.Disassemble(&my_addr
, len_addr
);
483 // --------------------------------------------------------------
484 // --------- wxSocketBase wait functions ------------------------
485 // --------------------------------------------------------------
486 void wxSocketBase::SaveState()
488 wxSockState
*state
= new wxSockState
;
490 state
->cbk_on
= m_cbkon
;
491 state
->cbk_set
= m_neededreq
;
493 state
->cdata
= m_cdata
;
494 state
->flags
= m_flags
;
495 state
->notif
= m_notifyme
;
497 m_states
.Append(state
);
500 void wxSocketBase::RestoreState()
504 node
= m_states
.Last();
508 wxSockState
*state
= (wxSockState
*)node
->Data();
510 SetFlags(state
->flags
);
511 m_neededreq
= state
->cbk_set
;
513 m_cdata
= state
->cdata
;
514 m_notifyme
= state
->notif
;
524 // --------------------------------------------------------------
525 // --------- wxSocketBase wait functions ------------------------
526 // --------------------------------------------------------------
528 bool wxSocketBase::_Wait(long seconds
, long microseconds
, int type
)
530 if ((!m_connected
&& !m_connecting
) || m_fd
< 0)
533 wxSockWakeUp
wakeup(this, &m_waitflags
, 0);
536 SetNotify((wxRequestNotify
)type
);
540 wakeup
.Start((int)(seconds
*1000 + (microseconds
/ 1000)), TRUE
);
542 m_waitflags
= 0x80 | type
;
543 while (m_waitflags
& 0x80)
548 if (m_waitflags
& 0x40) {
557 bool wxSocketBase::Wait(long seconds
, long microseconds
)
559 return _Wait(seconds
, microseconds
, REQ_ACCEPT
| REQ_CONNECT
|
560 REQ_READ
| REQ_WRITE
| REQ_LOST
);
563 bool wxSocketBase::WaitForRead(long seconds
, long microseconds
)
565 return _Wait(seconds
, microseconds
, REQ_READ
| REQ_LOST
);
568 bool wxSocketBase::WaitForWrite(long seconds
, long microseconds
)
570 return _Wait(seconds
, microseconds
, REQ_WRITE
);
573 bool wxSocketBase::WaitForLost(long seconds
, long microseconds
)
575 return _Wait(seconds
, microseconds
, REQ_LOST
);
578 // --------------------------------------------------------------
579 // --------- wxSocketBase callback management -------------------
580 // --------------------------------------------------------------
582 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
583 #if defined(__WXMOTIF__) || defined(__WXXT__)
584 static void wx_socket_read(XtPointer client
, int *fid
,
585 XtInputId
*WXUNUSED(id
))
588 static void wx_socket_read(gpointer client
, gint fd
,
589 GdkInputCondition
WXUNUSED(cond
))
593 wxSocketBase
*sock
= (wxSocketBase
*)client
;
597 i
= recv(fd
, &c
, 1, MSG_PEEK
);
599 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
)) {
600 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
605 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
608 sock
->OnRequest(wxSocketBase::EVT_READ
);
610 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
)) {
615 sock
->OnRequest(wxSocketBase::EVT_LOST
);
620 #if defined(__WXMOTIF__) || defined(__WXXT__)
621 static void wx_socket_write(XtPointer client
, int *WXUNUSED(fid
),
622 XtInputId
*WXUNUSED(id
))
624 static void wx_socket_write(gpointer client
, gint
WXUNUSED(fd
),
625 GdkInputCondition
WXUNUSED(cond
))
628 wxSocketBase
*sock
= (wxSocketBase
*)client
;
630 if (!sock
->IsConnected())
631 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
633 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
638 Notify_value
wx_sock_read_xview (Notify_client client
, int fd
)
640 wxSocketBase
*sock
= (wxSocketBase
*)client
;
644 i
= recv(fd
, &c
, 1, MSG_PEEK
);
646 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
)) {
647 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
653 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
654 return (Notify_value
) FALSE
;
656 sock
->OnRequest(wxSocketBase::EVT_READ
);
658 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
661 sock
->OnRequest(wxSocketBase::EVT_LOST
);
664 return (Notify_value
) FALSE
;
667 Notify_value
wx_sock_write_xview (Notify_client client
, int fd
)
669 wxSocketBase
*sock
= (wxSocketBase
*)client
;
671 if (!sock
->IsConnected())
672 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
674 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
676 return (Notify_value
) TRUE
;
680 wxSocketBase::wxRequestNotify
wxSocketBase::EventToNotify(wxRequestEvent evt
)
699 void wxSocketBase::SetFlags(wxSockFlags _flags
)
702 if (_flags
& SPEED
) {
703 unsigned long flag
= 0;
704 ioctl(m_fd
, FIONBIO
, &flag
);
706 // SPEED and WAITALL are antagonists.
707 m_flags
= (wxSockFlags
)(m_flags
& ~WAITALL
);
711 unsigned long flag
= 1;
712 ioctl(m_fd
, FIONBIO
, &flag
);
716 void wxSocketBase::SetNotify(wxRequestNotify flags
)
718 wxRequestNotify old_needed_req
= m_neededreq
;
719 if (flags
& REQ_ACCEPT
) {
720 /* Check if server */
721 if (!(GetClassInfo()->IsKindOf(CLASSINFO(wxSocketServer
))))
722 flags
&= ~REQ_ACCEPT
;
725 if (m_cbkon
&& old_needed_req
!= flags
)
729 void wxSocketBase::SetupCallbacks()
731 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| (m_flags
& SPEED
))
734 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
737 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
)) {
739 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_READ
,
740 wx_socket_read
, (gpointer
)this);
742 m_internal
->sock_inputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
743 (XtPointer
*) XtInputReadMask
,
744 (XtInputCallbackProc
) wx_socket_read
,
748 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
)) {
750 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_WRITE
,
751 wx_socket_write
, (gpointer
)this);
753 m_internal
->sock_outputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
754 (XtPointer
*) XtInputWriteMask
,
755 (XtInputCallbackProc
) wx_socket_write
,
763 if (m_neededreq
& REQ_READ
)
765 if (m_neededreq
& REQ_WRITE
)
767 if (m_neededreq
& REQ_LOST
)
769 if (m_neededreq
& REQ_ACCEPT
)
771 if (m_neededreq
& REQ_CONNECT
)
774 if (!m_internal
->my_msg
)
775 m_internal
->my_msg
= m_handler
->NewMessage(this);
776 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), m_internal
->my_msg
, mask
);
779 m_processing
= FALSE
;
782 void wxSocketBase::DestroyCallbacks()
784 if (!m_cbkon
|| !m_handler
)
787 m_processing
= FALSE
;
788 #if defined(__WXMOTIF__) || defined(__WXXT__)
789 if (m_internal
->sock_inputid
> 0)
790 XtRemoveInput(m_internal
->sock_inputid
);
791 m_internal
->sock_inputid
= 0;
792 if (m_internal
->sock_outputid
> 0)
793 XtRemoveInput(m_internal
->sock_outputid
);
794 m_internal
->sock_outputid
= 0;
797 if (m_internal
->sock_inputid
> 0)
798 gdk_input_remove(m_internal
->sock_inputid
);
799 m_internal
->sock_inputid
= 0;
800 if (m_internal
->sock_outputid
> 0)
801 gdk_input_remove(m_internal
->sock_outputid
);
802 m_internal
->sock_outputid
= 0;
805 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), 0, 0);
809 void wxSocketBase::Notify(bool notify
)
811 if (m_notifyme
== notify
)
820 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
822 wxRequestNotify req_notif
= EventToNotify(req_evt
);
824 // Mask the current event
825 SetNotify(m_neededreq
& ~req_notif
);
827 if (req_evt
<= EVT_WRITE
&& DoRequests(req_evt
))
830 if (m_waitflags
& 0xF0) {
832 if ((m_waitflags
& 0x0F) == req_evt
) {
835 DestroyCallbacks(); // I disable it to prevent infinite loop on X11.
841 if (req_evt
== EVT_LOST
) {
846 OldOnNotify(req_evt
);
849 SetNotify(m_neededreq
| req_notif
);
852 wxSocketEvent::wxSocketEvent(int id
)
855 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
860 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
862 wxSocketEvent
event(m_id
);
864 event
.SetEventObject(this);
869 m_cbk(*this, evt
, m_cdata
);
872 // --------------------------------------------------------------
873 // --------- wxSocketBase functions [Callback, CallbackData] ----
874 // --------------------------------------------------------------
875 wxSocketBase::wxSockCbk
wxSocketBase::Callback(wxSocketBase::wxSockCbk _cbk
)
877 wxSockCbk old_cbk
= m_cbk
;
883 char *wxSocketBase::CallbackData(char *cdata_
)
885 char *old_cdata
= m_cdata
;
891 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
893 SetNextHandler(&h_evt
);
897 // --------------------------------------------------------------
898 // --------- wxSocketBase pushback library ----------------------
899 // --------------------------------------------------------------
900 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
904 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
905 curr_pos
= m_unread
+ m_unrd_size
;
907 memcpy(curr_pos
, buffer
, size
);
911 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
913 char *curr_pos
, *new_buf
;
915 new_buf
= (char *) malloc(m_unrd_size
+size
);
916 curr_pos
= new_buf
+ size
;
918 memcpy(new_buf
, buffer
, size
);
919 memcpy(curr_pos
, m_unread
, m_unrd_size
);
926 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
931 if (size
> m_unrd_size
)
933 memcpy(buffer
, m_unread
, size
);
946 // --------------------------------------------------------------
947 // --------- wxSocketBase "multi-thread" core -------------------
948 // --------------------------------------------------------------
950 bool wxSocketBase::DoRequests(wxRequestEvent req_flag
)
952 wxNode
*node
= req_list
[req_flag
].First();
959 SockRequest
*req
= (SockRequest
*)node
->Data();
966 ret
= recv(m_fd
, req
->buffer
, req
->size
,
967 (req
->type
== EVT_PEEK
) ? MSG_PEEK
: 0);
974 if ((len
< req
->size
) && (m_flags
& WAITALL
)) {
978 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
979 req_list
[req_flag
].Insert(req
);
989 ret
= send(m_fd
, req
->buffer
, req
->size
, 0);
996 if ((len
< req
->size
) && (m_flags
& WAITALL
)) {
1000 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1001 req_list
[req_flag
].Insert(req
);
1016 void wxSocketBase::WantSpeedBuffer(char *buffer
, size_t nbytes
,
1024 ret
= recv(m_fd
, buffer
, nbytes
,
1025 (evt
== EVT_PEEK
) ? MSG_PEEK
: 0);
1028 ret
= send(m_fd
, buffer
, nbytes
, 0);
1038 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
1043 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
1046 if (m_flags
& SPEED
) {
1047 WantSpeedBuffer(buffer
, nbytes
, evt
);
1051 SockRequest
*buf
= new SockRequest
;
1052 wxSockWakeUp
s_wake(NULL
, (int *)&buf_timed_out
, (int)TRUE
);
1055 req_list
[evt
].Append(buf
);
1058 SetNotify(REQ_LOST
| EventToNotify(evt
));
1060 buf
->buffer
= buffer
;
1065 buf
->auto_wakeup
= &s_wake
;
1067 buf_timed_out
= FALSE
;
1069 s_wake
.Start(m_timeout
*1000, TRUE
);
1070 if (m_flags
& NOWAIT
) {
1073 while (!buf
->done
&& !buf_timed_out
)
1077 m_lcount
= buf
->nbytes
;
1079 m_error
= ETIMEDOUT
;
1081 m_error
= buf
->error
;
1087 // --------------------------------------------------------------
1088 // wxSocketServer ///////////////////////////////////////////////
1089 // --------------------------------------------------------------
1091 // --------------------------------------------------------------
1092 // --------- wxSocketServer CONSTRUCTOR -------------------------
1093 // --------------------------------------------------------------
1094 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1095 wxSockFlags flags
) :
1096 wxSocketBase(flags
, SOCK_SERVER
)
1098 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1100 if (m_fd
== INVALID_SOCKET
)
1104 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
1106 struct sockaddr
*myaddr
;
1109 addr_man
.Build(myaddr
, len
);
1110 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
1113 if (listen(m_fd
, 5) < 0) {
1114 m_fd
= INVALID_SOCKET
;
1119 // --------------------------------------------------------------
1120 // --------- wxSocketServer Accept ------------------------------
1121 // --------------------------------------------------------------
1122 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
1126 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
1129 struct linger linger
;
1131 linger
.l_linger
= 1;
1133 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1136 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1138 if (!(sock
.m_flags
& SPEED
)) {
1139 unsigned long flag2
= 1;
1140 ioctl(fd2
, FIONBIO
, &flag2
);
1143 sock
.m_type
= SOCK_INTERNAL
;
1145 sock
.m_connected
= TRUE
;
1150 wxSocketBase
*wxSocketServer::Accept()
1152 wxSocketBase
* sock
= new wxSocketBase();
1154 sock
->SetFlags((wxSockFlags
)m_flags
);
1156 if (!AcceptWith(*sock
))
1160 m_handler
->Register(sock
);
1165 // --------------------------------------------------------------
1166 // --------- wxSocketServer callbacks ---------------------------
1167 // --------------------------------------------------------------
1168 void wxSocketServer::OnRequest(wxRequestEvent evt
)
1170 if (evt
== EVT_ACCEPT
) {
1171 OldOnNotify(EVT_ACCEPT
);
1175 // --------------------------------------------------------------
1176 // wxSocketClient ///////////////////////////////////////////////
1177 // --------------------------------------------------------------
1179 // --------- wxSocketClient CONSTRUCTOR -------------------------
1180 // --------------------------------------------------------------
1181 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
1182 wxSocketBase(_flags
, SOCK_CLIENT
)
1186 // --------------------------------------------------------------
1187 // --------- wxSocketClient DESTRUCTOR --------------------------
1188 // --------------------------------------------------------------
1189 wxSocketClient::~wxSocketClient()
1193 // --------------------------------------------------------------
1194 // --------- wxSocketClient Connect functions -------------------
1195 // --------------------------------------------------------------
1196 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
1198 struct linger linger
;
1203 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1208 m_connected
= FALSE
;
1211 linger
.l_linger
= 5;
1212 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1214 // Stay in touch with the state of things...
1216 unsigned long flag
= 1;
1217 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1219 // Disable the nagle algorithm, which delays sends till the
1220 // buffer is full (or a certain time period has passed?)...
1222 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1224 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
1227 struct sockaddr
*remote
;
1230 addr_man
.Build(remote
, len
);
1232 if (connect(m_fd
, remote
, len
) != 0)
1235 if (!(m_flags
& SPEED
)) {
1237 ioctl(m_fd
, FIONBIO
, &flag
);
1246 bool wxSocketClient::WaitOnConnect(long seconds
)
1248 int ret
= _Wait(seconds
, 0, REQ_CONNECT
| REQ_LOST
);
1256 void wxSocketClient::OnRequest(wxRequestEvent evt
)
1258 if (evt
== EVT_CONNECT
) {
1260 SetNotify(m_neededreq
& ~REQ_CONNECT
);
1265 OldOnNotify(EVT_CONNECT
);
1269 wxSocketBase::OnRequest(evt
);
1272 /////////////////////////////////////////////////////////////////
1273 // wxSocketHandler ///////////////////////////////////////////////
1274 /////////////////////////////////////////////////////////////////
1276 wxSocketHandler
*wxSocketHandler::master
= NULL
;
1277 #if defined(__WINDOWS__)
1278 static int win_initialized
= 0;
1281 // --------------------------------------------------------------
1282 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1283 // --------------------------------------------------------------
1286 extern char wxPanelClassName
[];
1288 LRESULT APIENTRY _EXPORT
wxSocketHandlerWndProc(HWND hWnd
, UINT message
,
1289 WPARAM wParam
, LPARAM lParam
)
1291 wxSocketHandler
*h_sock
= (wxSocketHandler
*)GetWindowLong(hWnd
, GWL_USERDATA
);
1292 wxNode
*node
= h_sock
->smsg_list
->Find(message
);
1294 wxSocketBase::wxRequestEvent sk_req
;
1295 UINT event
= WSAGETSELECTEVENT(lParam
);
1298 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1300 sock
= (wxSocketBase
*)node
->Data();
1304 sk_req
= wxSocketBase::EVT_READ
;
1307 sk_req
= wxSocketBase::EVT_WRITE
;
1310 sk_req
= wxSocketBase::EVT_LOST
;
1313 sk_req
= wxSocketBase::EVT_ACCEPT
;
1316 sk_req
= wxSocketBase::EVT_CONNECT
;
1319 sock
->OnRequest(sk_req
);
1324 FARPROC wxSocketSubClassProc
= NULL
;
1328 wxSocketHandler::wxSocketHandler()
1330 #if defined(__WINDOWS__)
1331 if (!win_initialized
) {
1334 WSAStartup((1 << 8) | 1, &wsaData
);
1335 win_initialized
= 1;
1337 internal
= new wxSockHandlerInternal
;
1338 internal
->sockWin
= ::CreateWindow(wxPanelClassName
, NULL
, 0,
1339 0, 0, 0, 0, NULL
, (HMENU
) NULL
,
1342 // Subclass the window
1343 if (!wxSocketSubClassProc
)
1344 wxSocketSubClassProc
= MakeProcInstance((FARPROC
) wxSocketHandlerWndProc
, wxhInstance
);
1345 ::SetWindowLong(internal
->sockWin
, GWL_WNDPROC
, (LONG
) wxSocketSubClassProc
);
1346 ::SetWindowLong(internal
->sockWin
, GWL_USERDATA
, (LONG
) this);
1348 internal
->firstAvailableMsg
= 5000;
1349 smsg_list
= new wxList(wxKEY_INTEGER
);
1355 signal(SIGPIPE
, SIG_IGN
);
1359 // --------------------------------------------------------------
1360 // --------- wxSocketHandler DESTRUCTOR -------------------------
1361 // --------------------------------------------------------------
1362 wxSocketHandler::~wxSocketHandler()
1364 wxNode
*next_node
, *node
= socks
->First();
1367 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
1370 next_node
= node
->Next();
1380 ::DestroyWindow(internal
->sockWin
);
1382 win_initialized
= 0;
1388 // --------------------------------------------------------------
1389 // --------- wxSocketHandler registering functions --------------
1390 // --------------------------------------------------------------
1391 void wxSocketHandler::Register(wxSocketBase
* sock
)
1395 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next()) {
1396 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1403 socks
->Append(sock
);
1404 sock
->SetHandler(this);
1405 sock
->SetupCallbacks();
1409 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
1413 for (node
= socks
->First(); node
; node
= node
->Next()) {
1414 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1418 sock
->DestroyCallbacks();
1419 sock
->SetHandler(NULL
);
1425 unsigned long wxSocketHandler::Count() const
1427 return socks
->Number();
1430 // --------------------------------------------------------------
1431 // --------- wxSocketHandler "big" wait functions ---------------
1432 // --------------------------------------------------------------
1433 void handler_cbk(wxSocketBase
& sock
,
1434 wxSocketBase::wxRequestEvent
WXUNUSED(flags
),
1437 int *a_wait
= (int *)cdata
;
1443 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1447 wxSockWakeUp
s_wake(NULL
, &on_wait
, -2);
1450 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1451 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1455 sock
->SetupCallbacks();
1457 sock
->Callback(handler_cbk
);
1458 sock
->CallbackData((char *)&on_wait
);
1462 s_wake
.Start((seconds
*1000) + (microseconds
/1000), TRUE
);
1467 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1468 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1470 sock
->RestoreState();
1479 void wxSocketHandler::YieldSock()
1483 for (node
= socks
->First(); node
; node
= node
->Next() ) {
1484 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1488 sock
->SetFlags(wxSocketBase::SPEED
);
1490 sock
->DoRequests(wxSocketBase::EVT_READ
);
1491 sock
->DoRequests(wxSocketBase::EVT_WRITE
);
1493 sock
->RestoreState();
1497 // --------------------------------------------------------------
1498 // --------- wxSocketHandler: create and register the socket ----
1499 // --------------------------------------------------------------
1500 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1501 wxSocketBase::wxSockFlags flags
)
1503 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1509 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1511 wxSocketClient
*client
= new wxSocketClient(flags
);
1518 // --------------------------------------------------------------
1519 // --------- wxSocketHandler: Windows specific methods ----------
1520 // --------------------------------------------------------------
1521 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1523 internal
->firstAvailableMsg
++;
1524 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1525 return internal
->firstAvailableMsg
;
1528 void wxSocketHandler::DestroyMessage(UINT msg
)
1530 wxNode
*node
= smsg_list
->Find(msg
);
1534 HWND
wxSocketHandler::GetHWND() const
1536 return internal
->sockWin
;