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 #define WXSOCK_INTERNAL
93 #include "wx/sckaddr.h"
94 #include "wx/socket.h"
96 /////////////////////////////////////////////////////////////////////////////
97 // Some patch ///// BEGIN
98 /////////////////////////////////////////////////////////////////////////////
100 #define close closesocket
101 #define ioctl ioctlsocket
105 #define errno WSAGetLastError()
109 #define EWOULDBLOCK WSAEWOULDBLOCK
110 #define ETIMEDOUT WSAETIMEDOUT
112 #define EINTR WSAEINTR
116 #define INVALID_SOCKET -1
120 #define wxAPP_CONTEXT ((XtAppContext)wxTheApp->GetAppContext())
124 // This is an MS TCP/IP routine and is not needed here. Some WinSock
125 // implementations (such as PC-NFS) will require you to include this
126 // or a similar routine (see appendix in WinSock doc or help file).
128 #if defined( NEED_WSAFDIsSet ) || defined( _MSC_VER )
129 int PASCAL FAR
__WSAFDIsSet(SOCKET fd
, fd_set FAR
*set
)
131 int i
= set
->fd_count
;
135 if (set
->fd_array
[i
] == fd
)
144 #if defined(__WINDOWS__)
145 #define PROCESS_EVENTS() wxYield()
146 #elif defined(__WXXT__) || defined(__WXMOTIF__)
147 #define PROCESS_EVENTS() XtAppProcessEvent(wxAPP_CONTEXT, XtIMAll)
148 #elif defined(__WXGTK__)
149 #define PROCESS_EVENTS() gtk_main_iteration()
152 /////////////////////////////////////////////////////////////////////////////
153 // Some patch ///// END
154 /////////////////////////////////////////////////////////////////////////////
156 // --------------------------------------------------------------
158 // --------------------------------------------------------------
159 #if !USE_SHARED_LIBRARY
160 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
161 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
162 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
163 IMPLEMENT_CLASS(wxSocketHandler
, wxObject
)
164 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
167 class wxSockWakeUp
: public wxTimer
{
173 wxSockWakeUp(wxSocketBase
*_sock
, int *id
, int new_val
) {
174 my_id
= id
; n_val
= new_val
;
177 virtual void Notify() {
179 if (sock
) sock
->Notify(FALSE
);
184 class SockRequest
: public wxObject
{
190 wxSockWakeUp
*auto_wakeup
;
191 wxSocketBase::wxRequestNotify type
;
195 /////////////////////////////////////////////////////////////////////////////
196 // Some internal define
197 /////////////////////////////////////////////////////////////////////////////
199 // --------------------------------------------------------------
200 // --------- wxSocketBase CONSTRUCTOR ---------------------------
201 // --------------------------------------------------------------
202 wxSocketBase::wxSocketBase(wxSocketBase::wxSockFlags _flags
,
203 wxSocketBase::wxSockType _type
) :
205 m_flags(_flags
), m_type(_type
), m_connected(FALSE
), m_connecting(FALSE
),
206 m_fd(INVALID_SOCKET
), m_waitflags(0), m_cbk(0), m_cdata(0), m_id(-1),
208 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
210 m_unread(NULL
), m_unrd_size(0),
212 m_timeout(3600), m_wantbuf(0)
214 m_internal
= new wxSockInternal
;
215 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
216 m_internal
->sock_inputid
= 0;
217 m_internal
->sock_outputid
= 0;
218 m_internal
->sock_exceptid
= 0;
221 m_internal
->my_msg
= 0;
225 wxSocketBase::wxSocketBase() :
227 m_flags(WAITALL
), m_type(SOCK_UNINIT
), m_connected(FALSE
),
228 m_connecting(FALSE
), m_fd(INVALID_SOCKET
), m_waitflags(0),
229 m_cbk(0), m_cdata(0),
230 m_id(-1), m_handler(0),
231 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
233 m_unread(NULL
), m_unrd_size(0),
235 m_timeout(3600), m_wantbuf(0)
237 m_internal
= new wxSockInternal
;
238 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
239 m_internal
->sock_inputid
= 0;
240 m_internal
->sock_outputid
= 0;
241 m_internal
->sock_exceptid
= 0;
244 m_internal
->my_msg
= 0;
248 // --------------------------------------------------------------
249 // --------- wxSocketBase CONSTRUCTOR ---------------------------
250 // --------------------------------------------------------------
251 wxSocketBase::~wxSocketBase()
260 if (m_internal
->my_msg
)
261 m_handler
->DestroyMessage(m_internal
->my_msg
);
263 m_handler
->UnRegister(this);
265 m_states
.DeleteContents(TRUE
);
270 bool wxSocketBase::Close()
272 if (m_fd
!= INVALID_SOCKET
) {
273 for (int i
=0;i
<3;i
++) {
274 wxNode
*n
, *node
= req_list
[i
].First();
277 SockRequest
*req
= (SockRequest
*)node
->Data();
289 m_fd
= INVALID_SOCKET
;
296 // --------------------------------------------------------------
297 // --------- wxSocketBase base IO functions ---------------------
298 // --------------------------------------------------------------
299 wxSocketBase
& wxSocketBase::Read(char* buffer
, size_t nbytes
)
301 m_lcount
= GetPushback(buffer
, nbytes
, FALSE
);
303 // If we have got the whole needed buffer or if we don't want to
304 // wait then it returns immediately.
305 if (!nbytes
|| (m_lcount
&& !(m_flags
& WAITALL
)) )
308 WantBuffer(buffer
, nbytes
, EVT_READ
);
313 wxSocketBase
& wxSocketBase::Peek(char* buffer
, size_t nbytes
)
315 size_t nbytes_old
= nbytes
;
317 nbytes
-= GetPushback(buffer
, nbytes
, TRUE
);
319 m_lcount
= nbytes_old
;
323 WantBuffer(buffer
, nbytes
, EVT_PEEK
);
328 wxSocketBase
& wxSocketBase::Write(const char *buffer
, size_t nbytes
)
330 WantBuffer((char *)buffer
, nbytes
, EVT_WRITE
);
334 wxSocketBase
& wxSocketBase::ReadMsg(char* buffer
, size_t nbytes
)
337 size_t len
, len2
, sig
;
339 Read((char *)&msg
, sizeof(msg
));
340 if (m_lcount
!= sizeof(msg
))
343 sig
= msg
.sig
[0] & 0xff;
344 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
345 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
346 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
348 if (sig
!= 0xfeeddead)
350 len
= msg
.len
[0] & 0xff;
351 len
|= (size_t)(msg
.len
[1] & 0xff) << 8;
352 len
|= (size_t)(msg
.len
[2] & 0xff) << 16;
353 len
|= (size_t)(msg
.len
[3] & 0xff) << 24;
360 if (Read(buffer
, len
).LastCount() != len
)
362 if (len2
&& (Read(NULL
, len2
).LastCount() != len2
))
364 if (Read((char *)&msg
, sizeof(msg
)).LastCount() != sizeof(msg
))
367 sig
= msg
.sig
[0] & 0xff;
368 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
369 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
370 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
372 if (sig
!= 0xdeadfeed)
378 wxSocketBase
& wxSocketBase::WriteMsg(const char *buffer
, size_t nbytes
)
382 msg
.sig
[0] = (char) 0xad;
383 msg
.sig
[1] = (char) 0xde;
384 msg
.sig
[2] = (char) 0xed;
385 msg
.sig
[3] = (char) 0xfe;
387 msg
.len
[0] = (char) nbytes
& 0xff;
388 msg
.len
[1] = (char) (nbytes
>> 8) & 0xff;
389 msg
.len
[2] = (char) (nbytes
>> 16) & 0xff;
390 msg
.len
[3] = (char) (nbytes
>> 24) & 0xff;
392 if (Write((char *)&msg
, sizeof(msg
)).LastCount() < sizeof(msg
))
394 if (Write(buffer
, nbytes
).LastCount() < nbytes
)
397 msg
.sig
[0] = (char) 0xed;
398 msg
.sig
[1] = (char) 0xfe;
399 msg
.sig
[2] = (char) 0xad;
400 msg
.sig
[3] = (char) 0xde;
401 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = (char) 0;
402 Write((char *)&msg
, sizeof(msg
));
407 wxSocketBase
& wxSocketBase::Unread(const char *buffer
, size_t nbytes
)
409 CreatePushbackAfter(buffer
, nbytes
);
413 bool wxSocketBase::IsData() const
426 FD_SET(m_fd
, &sock_set
);
427 select(FD_SETSIZE
, &sock_set
, NULL
, NULL
, &tv
);
428 return (FD_ISSET(m_fd
, &sock_set
) != 0);
431 // ---------------------------------------------------------------------
432 // --------- wxSocketBase Discard(): deletes all byte in the input queue
433 // ---------------------------------------------------------------------
434 void wxSocketBase::Discard()
436 #define MAX_BUFSIZE (10*1024)
437 char *my_data
= new char[MAX_BUFSIZE
];
438 size_t recv_size
= MAX_BUFSIZE
;
441 SetFlags((wxSockFlags
)(NOWAIT
| SPEED
));
443 while (recv_size
== MAX_BUFSIZE
) {
444 recv_size
= Read(my_data
, MAX_BUFSIZE
).LastCount();
453 // --------------------------------------------------------------
454 // --------- wxSocketBase socket info functions -----------------
455 // --------------------------------------------------------------
456 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
458 struct sockaddr my_addr
;
459 size_t len_addr
= sizeof(my_addr
);
464 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, (int *)&len_addr
) < 0)
467 addr_man
.Disassemble(&my_addr
, len_addr
);
471 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
473 struct sockaddr my_addr
;
474 size_t len_addr
= sizeof(my_addr
);
479 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, (int *)&len_addr
) < 0)
482 addr_man
.Disassemble(&my_addr
, len_addr
);
486 // --------------------------------------------------------------
487 // --------- wxSocketBase wait functions ------------------------
488 // --------------------------------------------------------------
489 void wxSocketBase::SaveState()
491 wxSockState
*state
= new wxSockState
;
493 state
->cbk_on
= m_cbkon
;
494 state
->cbk_set
= m_neededreq
;
496 state
->cdata
= m_cdata
;
497 state
->flags
= m_flags
;
498 state
->notif
= m_notifyme
;
500 m_states
.Append(state
);
503 void wxSocketBase::RestoreState()
507 node
= m_states
.Last();
511 wxSockState
*state
= (wxSockState
*)node
->Data();
513 SetFlags(state
->flags
);
514 m_neededreq
= state
->cbk_set
;
516 m_cdata
= state
->cdata
;
517 m_notifyme
= state
->notif
;
527 // --------------------------------------------------------------
528 // --------- wxSocketBase wait functions ------------------------
529 // --------------------------------------------------------------
531 bool wxSocketBase::_Wait(long seconds
, long microseconds
, int type
)
533 if ((!m_connected
&& !m_connecting
) || m_fd
< 0)
536 wxSockWakeUp
wakeup(this, &m_waitflags
, 0);
539 SetNotify((wxRequestNotify
)type
);
543 wakeup
.Start((int)(seconds
*1000 + (microseconds
/ 1000)), TRUE
);
545 m_waitflags
= 0x80 | type
;
546 while (m_waitflags
& 0x80)
551 if (m_waitflags
& 0x40) {
560 bool wxSocketBase::Wait(long seconds
, long microseconds
)
562 return _Wait(seconds
, microseconds
, REQ_ACCEPT
| REQ_CONNECT
|
563 REQ_READ
| REQ_WRITE
| REQ_LOST
);
566 bool wxSocketBase::WaitForRead(long seconds
, long microseconds
)
568 return _Wait(seconds
, microseconds
, REQ_READ
| REQ_LOST
);
571 bool wxSocketBase::WaitForWrite(long seconds
, long microseconds
)
573 return _Wait(seconds
, microseconds
, REQ_WRITE
);
576 bool wxSocketBase::WaitForLost(long seconds
, long microseconds
)
578 return _Wait(seconds
, microseconds
, REQ_LOST
);
581 // --------------------------------------------------------------
582 // --------- wxSocketBase callback management -------------------
583 // --------------------------------------------------------------
585 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
586 #if defined(__WXMOTIF__) || defined(__WXXT__)
587 static void wx_socket_read(XtPointer client
, int *fid
,
588 XtInputId
*WXUNUSED(id
))
591 static void wx_socket_read(gpointer client
, gint fd
,
592 GdkInputCondition
WXUNUSED(cond
))
596 wxSocketBase
*sock
= (wxSocketBase
*)client
;
600 i
= recv(fd
, &c
, 1, MSG_PEEK
);
602 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
)) {
603 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
608 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
611 sock
->OnRequest(wxSocketBase::EVT_READ
);
613 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
)) {
618 sock
->OnRequest(wxSocketBase::EVT_LOST
);
623 #if defined(__WXMOTIF__) || defined(__WXXT__)
624 static void wx_socket_write(XtPointer client
, int *WXUNUSED(fid
),
625 XtInputId
*WXUNUSED(id
))
627 static void wx_socket_write(gpointer client
, gint
WXUNUSED(fd
),
628 GdkInputCondition
WXUNUSED(cond
))
631 wxSocketBase
*sock
= (wxSocketBase
*)client
;
633 if (!sock
->IsConnected())
634 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
636 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
641 Notify_value
wx_sock_read_xview (Notify_client client
, int fd
)
643 wxSocketBase
*sock
= (wxSocketBase
*)client
;
647 i
= recv(fd
, &c
, 1, MSG_PEEK
);
649 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
)) {
650 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
656 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
657 return (Notify_value
) FALSE
;
659 sock
->OnRequest(wxSocketBase::EVT_READ
);
661 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
664 sock
->OnRequest(wxSocketBase::EVT_LOST
);
667 return (Notify_value
) FALSE
;
670 Notify_value
wx_sock_write_xview (Notify_client client
, int fd
)
672 wxSocketBase
*sock
= (wxSocketBase
*)client
;
674 if (!sock
->IsConnected())
675 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
677 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
679 return (Notify_value
) TRUE
;
683 wxSocketBase::wxRequestNotify
wxSocketBase::EventToNotify(wxRequestEvent evt
)
702 void wxSocketBase::SetFlags(wxSockFlags _flags
)
705 if (_flags
& SPEED
) {
706 unsigned long flag
= 0;
707 ioctl(m_fd
, FIONBIO
, &flag
);
709 // SPEED and WAITALL are antagonists.
710 m_flags
= (wxSockFlags
)(m_flags
& ~WAITALL
);
714 unsigned long flag
= 1;
715 ioctl(m_fd
, FIONBIO
, &flag
);
719 void wxSocketBase::SetNotify(wxRequestNotify flags
)
721 wxRequestNotify old_needed_req
= m_neededreq
;
722 if (flags
& REQ_ACCEPT
) {
723 /* Check if server */
724 if (!(GetClassInfo()->IsKindOf(CLASSINFO(wxSocketServer
))))
725 flags
&= ~REQ_ACCEPT
;
728 if (m_cbkon
&& old_needed_req
!= flags
)
732 void wxSocketBase::SetupCallbacks()
734 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| (m_flags
& SPEED
))
737 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
740 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
)) {
742 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_READ
,
743 wx_socket_read
, (gpointer
)this);
745 m_internal
->sock_inputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
746 (XtPointer
*) XtInputReadMask
,
747 (XtInputCallbackProc
) wx_socket_read
,
751 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
)) {
753 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_WRITE
,
754 wx_socket_write
, (gpointer
)this);
756 m_internal
->sock_outputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
757 (XtPointer
*) XtInputWriteMask
,
758 (XtInputCallbackProc
) wx_socket_write
,
766 if (m_neededreq
& REQ_READ
)
768 if (m_neededreq
& REQ_WRITE
)
770 if (m_neededreq
& REQ_LOST
)
772 if (m_neededreq
& REQ_ACCEPT
)
774 if (m_neededreq
& REQ_CONNECT
)
777 if (!m_internal
->my_msg
)
778 m_internal
->my_msg
= m_handler
->NewMessage(this);
779 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), m_internal
->my_msg
, mask
);
782 m_processing
= FALSE
;
785 void wxSocketBase::DestroyCallbacks()
787 if (!m_cbkon
|| !m_handler
)
790 m_processing
= FALSE
;
791 #if defined(__WXMOTIF__) || defined(__WXXT__)
792 if (m_internal
->sock_inputid
> 0)
793 XtRemoveInput(m_internal
->sock_inputid
);
794 m_internal
->sock_inputid
= 0;
795 if (m_internal
->sock_outputid
> 0)
796 XtRemoveInput(m_internal
->sock_outputid
);
797 m_internal
->sock_outputid
= 0;
800 if (m_internal
->sock_inputid
> 0)
801 gdk_input_remove(m_internal
->sock_inputid
);
802 m_internal
->sock_inputid
= 0;
803 if (m_internal
->sock_outputid
> 0)
804 gdk_input_remove(m_internal
->sock_outputid
);
805 m_internal
->sock_outputid
= 0;
808 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), 0, 0);
812 void wxSocketBase::Notify(bool notify
)
814 if (m_notifyme
== notify
)
823 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
825 wxRequestNotify req_notif
= EventToNotify(req_evt
);
827 // Mask the current event
828 SetNotify(m_neededreq
& ~req_notif
);
830 if (req_evt
<= EVT_WRITE
&& DoRequests(req_evt
))
833 if (m_waitflags
& 0xF0) {
835 if ((m_waitflags
& 0x0F) == req_evt
) {
838 DestroyCallbacks(); // I disable it to prevent infinite loop on X11.
844 if (req_evt
== EVT_LOST
) {
849 OldOnNotify(req_evt
);
852 SetNotify(m_neededreq
| req_notif
);
855 wxSocketEvent::wxSocketEvent(int id
)
858 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
863 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
865 wxSocketEvent
event(m_id
);
867 event
.SetEventObject(this);
872 m_cbk(*this, evt
, m_cdata
);
875 // --------------------------------------------------------------
876 // --------- wxSocketBase functions [Callback, CallbackData] ----
877 // --------------------------------------------------------------
878 wxSocketBase::wxSockCbk
wxSocketBase::Callback(wxSocketBase::wxSockCbk _cbk
)
880 wxSockCbk old_cbk
= m_cbk
;
886 char *wxSocketBase::CallbackData(char *cdata_
)
888 char *old_cdata
= m_cdata
;
894 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
896 SetNextHandler(&h_evt
);
900 // --------------------------------------------------------------
901 // --------- wxSocketBase pushback library ----------------------
902 // --------------------------------------------------------------
903 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
907 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
908 curr_pos
= m_unread
+ m_unrd_size
;
910 memcpy(curr_pos
, buffer
, size
);
914 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
916 char *curr_pos
, *new_buf
;
918 new_buf
= (char *) malloc(m_unrd_size
+size
);
919 curr_pos
= new_buf
+ size
;
921 memcpy(new_buf
, buffer
, size
);
922 memcpy(curr_pos
, m_unread
, m_unrd_size
);
929 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
934 if (size
> m_unrd_size
)
936 memcpy(buffer
, m_unread
, size
);
949 // --------------------------------------------------------------
950 // --------- wxSocketBase "multi-thread" core -------------------
951 // --------------------------------------------------------------
953 bool wxSocketBase::DoRequests(wxRequestEvent req_flag
)
955 wxNode
*node
= req_list
[req_flag
].First();
962 SockRequest
*req
= (SockRequest
*)node
->Data();
969 ret
= recv(m_fd
, req
->buffer
, req
->size
,
970 (req
->type
== EVT_PEEK
) ? MSG_PEEK
: 0);
977 if ((len
< req
->size
) && (m_flags
& WAITALL
)) {
981 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
982 req_list
[req_flag
].Insert(req
);
992 ret
= send(m_fd
, req
->buffer
, req
->size
, 0);
999 if ((len
< req
->size
) && (m_flags
& WAITALL
)) {
1003 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1004 req_list
[req_flag
].Insert(req
);
1019 void wxSocketBase::WantSpeedBuffer(char *buffer
, size_t nbytes
,
1027 ret
= recv(m_fd
, buffer
, nbytes
,
1028 (evt
== EVT_PEEK
) ? MSG_PEEK
: 0);
1031 ret
= send(m_fd
, buffer
, nbytes
, 0);
1043 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
1048 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
1051 if (m_flags
& SPEED
) {
1052 WantSpeedBuffer(buffer
, nbytes
, evt
);
1056 SockRequest
*buf
= new SockRequest
;
1057 wxSockWakeUp
s_wake(NULL
, (int *)&buf_timed_out
, (int)TRUE
);
1060 req_list
[evt
].Append(buf
);
1063 SetNotify(REQ_LOST
| EventToNotify(evt
));
1065 buf
->buffer
= buffer
;
1070 buf
->auto_wakeup
= &s_wake
;
1072 buf_timed_out
= FALSE
;
1074 s_wake
.Start(m_timeout
*1000, TRUE
);
1075 if (m_flags
& NOWAIT
) {
1078 while (!buf
->done
&& !buf_timed_out
)
1082 m_lcount
= buf
->nbytes
;
1084 m_error
= ETIMEDOUT
;
1086 m_error
= buf
->error
;
1092 // --------------------------------------------------------------
1093 // wxSocketServer ///////////////////////////////////////////////
1094 // --------------------------------------------------------------
1096 // --------------------------------------------------------------
1097 // --------- wxSocketServer CONSTRUCTOR -------------------------
1098 // --------------------------------------------------------------
1099 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1100 wxSockFlags flags
) :
1101 wxSocketBase(flags
, SOCK_SERVER
)
1103 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1105 if (m_fd
== INVALID_SOCKET
)
1109 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
1111 struct sockaddr
*myaddr
;
1114 addr_man
.Build(myaddr
, len
);
1115 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
1118 if (listen(m_fd
, 5) < 0) {
1119 m_fd
= INVALID_SOCKET
;
1124 // --------------------------------------------------------------
1125 // --------- wxSocketServer Accept ------------------------------
1126 // --------------------------------------------------------------
1127 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
1131 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
1134 struct linger linger
;
1136 linger
.l_linger
= 1;
1138 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1141 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1143 if (!(sock
.m_flags
& SPEED
)) {
1144 unsigned long flag2
= 1;
1145 ioctl(fd2
, FIONBIO
, &flag2
);
1148 sock
.m_type
= SOCK_INTERNAL
;
1150 sock
.m_connected
= TRUE
;
1155 wxSocketBase
*wxSocketServer::Accept()
1157 wxSocketBase
* sock
= new wxSocketBase();
1159 sock
->SetFlags((wxSockFlags
)m_flags
);
1161 if (!AcceptWith(*sock
))
1165 m_handler
->Register(sock
);
1170 // --------------------------------------------------------------
1171 // --------- wxSocketServer callbacks ---------------------------
1172 // --------------------------------------------------------------
1173 void wxSocketServer::OnRequest(wxRequestEvent evt
)
1175 if (evt
== EVT_ACCEPT
) {
1176 OldOnNotify(EVT_ACCEPT
);
1180 // --------------------------------------------------------------
1181 // wxSocketClient ///////////////////////////////////////////////
1182 // --------------------------------------------------------------
1184 // --------- wxSocketClient CONSTRUCTOR -------------------------
1185 // --------------------------------------------------------------
1186 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
1187 wxSocketBase(_flags
, SOCK_CLIENT
)
1191 // --------------------------------------------------------------
1192 // --------- wxSocketClient DESTRUCTOR --------------------------
1193 // --------------------------------------------------------------
1194 wxSocketClient::~wxSocketClient()
1198 // --------------------------------------------------------------
1199 // --------- wxSocketClient Connect functions -------------------
1200 // --------------------------------------------------------------
1201 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
1203 struct linger linger
;
1208 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1213 m_connected
= FALSE
;
1216 linger
.l_linger
= 5;
1217 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1219 // Stay in touch with the state of things...
1221 unsigned long flag
= 1;
1222 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1224 // Disable the nagle algorithm, which delays sends till the
1225 // buffer is full (or a certain time period has passed?)...
1227 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1229 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
1232 struct sockaddr
*remote
;
1235 addr_man
.Build(remote
, len
);
1237 if (connect(m_fd
, remote
, len
) != 0)
1240 if (!(m_flags
& SPEED
)) {
1242 ioctl(m_fd
, FIONBIO
, &flag
);
1251 bool wxSocketClient::WaitOnConnect(long seconds
, long microseconds
)
1253 int ret
= _Wait(seconds
, microseconds
, REQ_CONNECT
| REQ_LOST
);
1261 void wxSocketClient::OnRequest(wxRequestEvent evt
)
1263 if (evt
== EVT_CONNECT
) {
1265 SetNotify(m_neededreq
& ~REQ_CONNECT
);
1270 OldOnNotify(EVT_CONNECT
);
1274 wxSocketBase::OnRequest(evt
);
1277 /////////////////////////////////////////////////////////////////
1278 // wxSocketHandler ///////////////////////////////////////////////
1279 /////////////////////////////////////////////////////////////////
1281 wxSocketHandler
*wxSocketHandler::master
= NULL
;
1282 #if defined(__WINDOWS__)
1283 static int win_initialized
= 0;
1286 // --------------------------------------------------------------
1287 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1288 // --------------------------------------------------------------
1291 extern char wxPanelClassName
[];
1293 LRESULT APIENTRY _EXPORT
wxSocketHandlerWndProc(HWND hWnd
, UINT message
,
1294 WPARAM wParam
, LPARAM lParam
)
1296 wxSocketHandler
*h_sock
= (wxSocketHandler
*)GetWindowLong(hWnd
, GWL_USERDATA
);
1297 wxNode
*node
= h_sock
->smsg_list
->Find(message
);
1299 wxSocketBase::wxRequestEvent sk_req
;
1300 UINT event
= WSAGETSELECTEVENT(lParam
);
1303 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1305 sock
= (wxSocketBase
*)node
->Data();
1309 sk_req
= wxSocketBase::EVT_READ
;
1312 sk_req
= wxSocketBase::EVT_WRITE
;
1315 sk_req
= wxSocketBase::EVT_LOST
;
1318 sk_req
= wxSocketBase::EVT_ACCEPT
;
1321 sk_req
= wxSocketBase::EVT_CONNECT
;
1324 sock
->OnRequest(sk_req
);
1329 FARPROC wxSocketSubClassProc
= NULL
;
1333 wxSocketHandler::wxSocketHandler()
1335 #if defined(__WINDOWS__)
1336 if (!win_initialized
) {
1339 WSAStartup((1 << 8) | 1, &wsaData
);
1340 win_initialized
= 1;
1342 internal
= new wxSockHandlerInternal
;
1343 internal
->sockWin
= ::CreateWindow(wxPanelClassName
, NULL
, 0,
1344 0, 0, 0, 0, NULL
, (HMENU
) NULL
,
1347 // Subclass the window
1348 if (!wxSocketSubClassProc
)
1349 wxSocketSubClassProc
= MakeProcInstance((FARPROC
) wxSocketHandlerWndProc
, wxhInstance
);
1350 ::SetWindowLong(internal
->sockWin
, GWL_WNDPROC
, (LONG
) wxSocketSubClassProc
);
1351 ::SetWindowLong(internal
->sockWin
, GWL_USERDATA
, (LONG
) this);
1353 internal
->firstAvailableMsg
= 5000;
1354 smsg_list
= new wxList(wxKEY_INTEGER
);
1360 signal(SIGPIPE
, SIG_IGN
);
1364 // --------------------------------------------------------------
1365 // --------- wxSocketHandler DESTRUCTOR -------------------------
1366 // --------------------------------------------------------------
1367 wxSocketHandler::~wxSocketHandler()
1369 wxNode
*next_node
, *node
= socks
->First();
1372 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
1375 next_node
= node
->Next();
1385 ::DestroyWindow(internal
->sockWin
);
1387 win_initialized
= 0;
1393 // --------------------------------------------------------------
1394 // --------- wxSocketHandler registering functions --------------
1395 // --------------------------------------------------------------
1396 void wxSocketHandler::Register(wxSocketBase
* sock
)
1400 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next()) {
1401 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1408 socks
->Append(sock
);
1409 sock
->SetHandler(this);
1410 sock
->SetupCallbacks();
1414 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
1418 for (node
= socks
->First(); node
; node
= node
->Next()) {
1419 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1423 sock
->DestroyCallbacks();
1424 sock
->SetHandler(NULL
);
1430 unsigned long wxSocketHandler::Count() const
1432 return socks
->Number();
1435 // --------------------------------------------------------------
1436 // --------- wxSocketHandler "big" wait functions ---------------
1437 // --------------------------------------------------------------
1438 void handler_cbk(wxSocketBase
& sock
,
1439 wxSocketBase::wxRequestEvent
WXUNUSED(flags
),
1442 int *a_wait
= (int *)cdata
;
1448 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1452 wxSockWakeUp
s_wake(NULL
, &on_wait
, -2);
1455 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1456 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1460 sock
->SetupCallbacks();
1462 sock
->Callback(handler_cbk
);
1463 sock
->CallbackData((char *)&on_wait
);
1467 s_wake
.Start((seconds
*1000) + (microseconds
/1000), TRUE
);
1472 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1473 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1475 sock
->RestoreState();
1484 void wxSocketHandler::YieldSock()
1488 for (node
= socks
->First(); node
; node
= node
->Next() ) {
1489 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1493 sock
->SetFlags(wxSocketBase::SPEED
);
1495 sock
->DoRequests(wxSocketBase::EVT_READ
);
1496 sock
->DoRequests(wxSocketBase::EVT_WRITE
);
1498 sock
->RestoreState();
1502 // --------------------------------------------------------------
1503 // --------- wxSocketHandler: create and register the socket ----
1504 // --------------------------------------------------------------
1505 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1506 wxSocketBase::wxSockFlags flags
)
1508 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1514 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1516 wxSocketClient
*client
= new wxSocketClient(flags
);
1523 // --------------------------------------------------------------
1524 // --------- wxSocketHandler: Windows specific methods ----------
1525 // --------------------------------------------------------------
1526 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1528 internal
->firstAvailableMsg
++;
1529 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1530 return internal
->firstAvailableMsg
;
1533 void wxSocketHandler::DestroyMessage(UINT msg
)
1535 wxNode
*node
= smsg_list
->Find(msg
);
1539 HWND
wxSocketHandler::GetHWND() const
1541 return internal
->sockWin
;