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);
1041 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
1046 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
1049 if (m_flags
& SPEED
) {
1050 WantSpeedBuffer(buffer
, nbytes
, evt
);
1054 SockRequest
*buf
= new SockRequest
;
1055 wxSockWakeUp
s_wake(NULL
, (int *)&buf_timed_out
, (int)TRUE
);
1058 req_list
[evt
].Append(buf
);
1061 SetNotify(REQ_LOST
| EventToNotify(evt
));
1063 buf
->buffer
= buffer
;
1068 buf
->auto_wakeup
= &s_wake
;
1070 buf_timed_out
= FALSE
;
1072 s_wake
.Start(m_timeout
*1000, TRUE
);
1073 if (m_flags
& NOWAIT
) {
1076 while (!buf
->done
&& !buf_timed_out
)
1080 m_lcount
= buf
->nbytes
;
1082 m_error
= ETIMEDOUT
;
1084 m_error
= buf
->error
;
1090 // --------------------------------------------------------------
1091 // wxSocketServer ///////////////////////////////////////////////
1092 // --------------------------------------------------------------
1094 // --------------------------------------------------------------
1095 // --------- wxSocketServer CONSTRUCTOR -------------------------
1096 // --------------------------------------------------------------
1097 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1098 wxSockFlags flags
) :
1099 wxSocketBase(flags
, SOCK_SERVER
)
1101 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1103 if (m_fd
== INVALID_SOCKET
)
1107 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
1109 struct sockaddr
*myaddr
;
1112 addr_man
.Build(myaddr
, len
);
1113 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
1116 if (listen(m_fd
, 5) < 0) {
1117 m_fd
= INVALID_SOCKET
;
1122 // --------------------------------------------------------------
1123 // --------- wxSocketServer Accept ------------------------------
1124 // --------------------------------------------------------------
1125 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
1129 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
1132 struct linger linger
;
1134 linger
.l_linger
= 1;
1136 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1139 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1141 if (!(sock
.m_flags
& SPEED
)) {
1142 unsigned long flag2
= 1;
1143 ioctl(fd2
, FIONBIO
, &flag2
);
1146 sock
.m_type
= SOCK_INTERNAL
;
1148 sock
.m_connected
= TRUE
;
1153 wxSocketBase
*wxSocketServer::Accept()
1155 wxSocketBase
* sock
= new wxSocketBase();
1157 sock
->SetFlags((wxSockFlags
)m_flags
);
1159 if (!AcceptWith(*sock
))
1163 m_handler
->Register(sock
);
1168 // --------------------------------------------------------------
1169 // --------- wxSocketServer callbacks ---------------------------
1170 // --------------------------------------------------------------
1171 void wxSocketServer::OnRequest(wxRequestEvent evt
)
1173 if (evt
== EVT_ACCEPT
) {
1174 OldOnNotify(EVT_ACCEPT
);
1178 // --------------------------------------------------------------
1179 // wxSocketClient ///////////////////////////////////////////////
1180 // --------------------------------------------------------------
1182 // --------- wxSocketClient CONSTRUCTOR -------------------------
1183 // --------------------------------------------------------------
1184 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
1185 wxSocketBase(_flags
, SOCK_CLIENT
)
1189 // --------------------------------------------------------------
1190 // --------- wxSocketClient DESTRUCTOR --------------------------
1191 // --------------------------------------------------------------
1192 wxSocketClient::~wxSocketClient()
1196 // --------------------------------------------------------------
1197 // --------- wxSocketClient Connect functions -------------------
1198 // --------------------------------------------------------------
1199 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
1201 struct linger linger
;
1206 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1211 m_connected
= FALSE
;
1214 linger
.l_linger
= 5;
1215 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1217 // Stay in touch with the state of things...
1219 unsigned long flag
= 1;
1220 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1222 // Disable the nagle algorithm, which delays sends till the
1223 // buffer is full (or a certain time period has passed?)...
1225 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1227 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
1230 struct sockaddr
*remote
;
1233 addr_man
.Build(remote
, len
);
1235 if (connect(m_fd
, remote
, len
) != 0)
1238 if (!(m_flags
& SPEED
)) {
1240 ioctl(m_fd
, FIONBIO
, &flag
);
1249 bool wxSocketClient::WaitOnConnect(long seconds
)
1251 int ret
= _Wait(seconds
, 0, REQ_CONNECT
| REQ_LOST
);
1259 void wxSocketClient::OnRequest(wxRequestEvent evt
)
1261 if (evt
== EVT_CONNECT
) {
1263 SetNotify(m_neededreq
& ~REQ_CONNECT
);
1268 OldOnNotify(EVT_CONNECT
);
1272 wxSocketBase::OnRequest(evt
);
1275 /////////////////////////////////////////////////////////////////
1276 // wxSocketHandler ///////////////////////////////////////////////
1277 /////////////////////////////////////////////////////////////////
1279 wxSocketHandler
*wxSocketHandler::master
= NULL
;
1280 #if defined(__WINDOWS__)
1281 static int win_initialized
= 0;
1284 // --------------------------------------------------------------
1285 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1286 // --------------------------------------------------------------
1289 extern char wxPanelClassName
[];
1291 LRESULT APIENTRY _EXPORT
wxSocketHandlerWndProc(HWND hWnd
, UINT message
,
1292 WPARAM wParam
, LPARAM lParam
)
1294 wxSocketHandler
*h_sock
= (wxSocketHandler
*)GetWindowLong(hWnd
, GWL_USERDATA
);
1295 wxNode
*node
= h_sock
->smsg_list
->Find(message
);
1297 wxSocketBase::wxRequestEvent sk_req
;
1298 UINT event
= WSAGETSELECTEVENT(lParam
);
1301 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1303 sock
= (wxSocketBase
*)node
->Data();
1307 sk_req
= wxSocketBase::EVT_READ
;
1310 sk_req
= wxSocketBase::EVT_WRITE
;
1313 sk_req
= wxSocketBase::EVT_LOST
;
1316 sk_req
= wxSocketBase::EVT_ACCEPT
;
1319 sk_req
= wxSocketBase::EVT_CONNECT
;
1322 sock
->OnRequest(sk_req
);
1327 FARPROC wxSocketSubClassProc
= NULL
;
1331 wxSocketHandler::wxSocketHandler()
1333 #if defined(__WINDOWS__)
1334 if (!win_initialized
) {
1337 WSAStartup((1 << 8) | 1, &wsaData
);
1338 win_initialized
= 1;
1340 internal
= new wxSockHandlerInternal
;
1341 internal
->sockWin
= ::CreateWindow(wxPanelClassName
, NULL
, 0,
1342 0, 0, 0, 0, NULL
, (HMENU
) NULL
,
1345 // Subclass the window
1346 if (!wxSocketSubClassProc
)
1347 wxSocketSubClassProc
= MakeProcInstance((FARPROC
) wxSocketHandlerWndProc
, wxhInstance
);
1348 ::SetWindowLong(internal
->sockWin
, GWL_WNDPROC
, (LONG
) wxSocketSubClassProc
);
1349 ::SetWindowLong(internal
->sockWin
, GWL_USERDATA
, (LONG
) this);
1351 internal
->firstAvailableMsg
= 5000;
1352 smsg_list
= new wxList(wxKEY_INTEGER
);
1358 signal(SIGPIPE
, SIG_IGN
);
1362 // --------------------------------------------------------------
1363 // --------- wxSocketHandler DESTRUCTOR -------------------------
1364 // --------------------------------------------------------------
1365 wxSocketHandler::~wxSocketHandler()
1367 wxNode
*next_node
, *node
= socks
->First();
1370 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
1373 next_node
= node
->Next();
1383 ::DestroyWindow(internal
->sockWin
);
1385 win_initialized
= 0;
1391 // --------------------------------------------------------------
1392 // --------- wxSocketHandler registering functions --------------
1393 // --------------------------------------------------------------
1394 void wxSocketHandler::Register(wxSocketBase
* sock
)
1398 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next()) {
1399 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1406 socks
->Append(sock
);
1407 sock
->SetHandler(this);
1408 sock
->SetupCallbacks();
1412 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
1416 for (node
= socks
->First(); node
; node
= node
->Next()) {
1417 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1421 sock
->DestroyCallbacks();
1422 sock
->SetHandler(NULL
);
1428 unsigned long wxSocketHandler::Count() const
1430 return socks
->Number();
1433 // --------------------------------------------------------------
1434 // --------- wxSocketHandler "big" wait functions ---------------
1435 // --------------------------------------------------------------
1436 void handler_cbk(wxSocketBase
& sock
,
1437 wxSocketBase::wxRequestEvent
WXUNUSED(flags
),
1440 int *a_wait
= (int *)cdata
;
1446 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1450 wxSockWakeUp
s_wake(NULL
, &on_wait
, -2);
1453 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1454 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1458 sock
->SetupCallbacks();
1460 sock
->Callback(handler_cbk
);
1461 sock
->CallbackData((char *)&on_wait
);
1465 s_wake
.Start((seconds
*1000) + (microseconds
/1000), TRUE
);
1470 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1471 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1473 sock
->RestoreState();
1482 void wxSocketHandler::YieldSock()
1486 for (node
= socks
->First(); node
; node
= node
->Next() ) {
1487 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1491 sock
->SetFlags(wxSocketBase::SPEED
);
1493 sock
->DoRequests(wxSocketBase::EVT_READ
);
1494 sock
->DoRequests(wxSocketBase::EVT_WRITE
);
1496 sock
->RestoreState();
1500 // --------------------------------------------------------------
1501 // --------- wxSocketHandler: create and register the socket ----
1502 // --------------------------------------------------------------
1503 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1504 wxSocketBase::wxSockFlags flags
)
1506 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1512 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1514 wxSocketClient
*client
= new wxSocketClient(flags
);
1521 // --------------------------------------------------------------
1522 // --------- wxSocketHandler: Windows specific methods ----------
1523 // --------------------------------------------------------------
1524 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1526 internal
->firstAvailableMsg
++;
1527 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1528 return internal
->firstAvailableMsg
;
1531 void wxSocketHandler::DestroyMessage(UINT msg
)
1533 wxNode
*node
= smsg_list
->Find(msg
);
1537 HWND
wxSocketHandler::GetHWND() const
1539 return internal
->sockWin
;