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 /////////////////////////////////////////////////////////////////////////////
20 /////////////////////////////////////////////////////////////////////////////
22 #include <wx/object.h>
23 #include <wx/string.h>
31 /////////////////////////////////////////////////////////////////////////////
32 // System specific headers
33 /////////////////////////////////////////////////////////////////////////////
34 #if defined(__WINDOWS__)
43 #include <sys/socket.h>
45 #include <sys/ioctl.h>
55 #if defined(__WXMOTIF__) || defined(__WXXT__)
56 #include <X11/Intrinsic.h>
58 /////////////////////////////
59 // Needs internal variables
60 /////////////////////////////
62 #define Uses_XtIntrinsic
67 #if defined(__WXGTK__)
71 /////////////////////////////////////////////////////////////////////////////
73 /////////////////////////////////////////////////////////////////////////////
74 #define WXSOCK_INTERNAL
75 #include "wx/sckaddr.h"
76 #include "wx/socket.h"
82 /////////////////////////////////////////////////////////////////////////////
83 // Some patch ///// BEGIN
84 /////////////////////////////////////////////////////////////////////////////
86 #define close closesocket
87 #define ioctl ioctlsocket
88 #define errno WSAGetLastError()
92 #define EWOULDBLOCK WSAEWOULDBLOCK
93 #define ETIMEDOUT WSAETIMEDOUT
95 #define EINTR WSAEINTR
99 #define INVALID_SOCKET -1
103 #define wxAPP_CONTEXT wxTheApp->appContext
107 // This is an MS TCP/IP routine and is not needed here. Some WinSock
108 // implementations (such as PC-NFS) will require you to include this
109 // or a similar routine (see appendix in WinSock doc or help file).
111 #if defined( NEED_WSAFDIsSet ) || defined( _MSC_VER )
112 int PASCAL FAR
__WSAFDIsSet(SOCKET fd
, fd_set FAR
*set
)
114 int i
= set
->fd_count
;
118 if (set
->fd_array
[i
] == fd
)
127 #if defined(__WINDOWS__)
128 #define PROCESS_EVENTS() wxYield()
129 #elif defined(__WXXT__) || defined(__WXMOTIF__)
130 #define PROCESS_EVENTS() XtAppProcessEvent(wxAPP_CONTEXT, XtIMAll)
131 #elif defined(__WXGTK__)
132 #define PROCESS_EVENTS() gtk_main_iteration()
135 /////////////////////////////////////////////////////////////////////////////
136 // Some patch ///// END
137 /////////////////////////////////////////////////////////////////////////////
139 // --------------------------------------------------------------
141 // --------------------------------------------------------------
142 #if !USE_SHARED_LIBRARY
143 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
144 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
145 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
146 IMPLEMENT_CLASS(wxSocketHandler
, wxObject
)
147 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
150 class wxSockWakeUp
: public wxTimer
{
156 wxSockWakeUp(wxSocketBase
*_sock
, int *id
, int new_val
) {
157 my_id
= id
; n_val
= new_val
;
160 virtual void Notify() {
162 if (sock
) sock
->Notify(FALSE
);
167 class SockRequest
: public wxObject
{
173 wxSockWakeUp
*auto_wakeup
;
174 wxSocketBase::wxRequestNotify type
;
178 /////////////////////////////////////////////////////////////////////////////
179 // Some internal define
180 /////////////////////////////////////////////////////////////////////////////
182 // --------------------------------------------------------------
183 // --------- wxSocketBase CONSTRUCTOR ---------------------------
184 // --------------------------------------------------------------
185 wxSocketBase::wxSocketBase(wxSocketBase::wxSockFlags _flags
,
186 wxSocketBase::wxSockType _type
) :
188 m_flags(_flags
), m_type(_type
), m_connected(FALSE
), m_connecting(FALSE
),
189 m_fd(INVALID_SOCKET
), m_waitflags(0), m_cbk(0), m_cdata(0), m_id(-1),
191 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
193 m_unread(NULL
), m_unrd_size(0),
195 m_timeout(3600), m_wantbuf(0)
197 m_internal
= new wxSockInternal
;
198 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
199 m_internal
->sock_inputid
= 0;
200 m_internal
->sock_outputid
= 0;
201 m_internal
->sock_exceptid
= 0;
204 m_internal
->my_msg
= 0;
208 wxSocketBase::wxSocketBase() :
210 m_flags(WAITALL
), m_type(SOCK_UNINIT
), m_connected(FALSE
),
211 m_connecting(FALSE
), m_fd(INVALID_SOCKET
), m_waitflags(0),
212 m_cbk(0), m_cdata(0),
213 m_id(-1), m_handler(0),
214 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
216 m_unread(NULL
), m_unrd_size(0),
218 m_timeout(3600), m_wantbuf(0)
220 m_internal
= new wxSockInternal
;
221 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
222 m_internal
->sock_inputid
= 0;
223 m_internal
->sock_outputid
= 0;
224 m_internal
->sock_exceptid
= 0;
227 m_internal
->my_msg
= 0;
231 // --------------------------------------------------------------
232 // --------- wxSocketBase CONSTRUCTOR ---------------------------
233 // --------------------------------------------------------------
234 wxSocketBase::~wxSocketBase()
243 if (m_internal
->my_msg
)
244 m_handler
->DestroyMessage(m_internal
->my_msg
);
246 m_handler
->UnRegister(this);
248 m_states
.DeleteContents(TRUE
);
253 bool wxSocketBase::Close()
255 if (m_fd
!= INVALID_SOCKET
) {
256 for (int i
=0;i
<3;i
++) {
257 wxNode
*n
, *node
= req_list
[i
].First();
260 SockRequest
*req
= (SockRequest
*)node
->Data();
272 m_fd
= INVALID_SOCKET
;
279 // --------------------------------------------------------------
280 // --------- wxSocketBase base IO functions ---------------------
281 // --------------------------------------------------------------
282 wxSocketBase
& wxSocketBase::Read(char* buffer
, size_t nbytes
)
284 m_lcount
= GetPushback(buffer
, nbytes
, FALSE
);
286 // If we have got the whole needed buffer or if we don't want to
287 // wait then it returns immediately.
288 if (!nbytes
|| (m_lcount
&& !(m_flags
& WAITALL
)) )
291 WantBuffer(buffer
, nbytes
, EVT_READ
);
296 wxSocketBase
& wxSocketBase::Peek(char* buffer
, size_t nbytes
)
298 size_t nbytes_old
= nbytes
;
300 nbytes
-= GetPushback(buffer
, nbytes
, TRUE
);
302 m_lcount
= nbytes_old
;
306 WantBuffer(buffer
, nbytes
, EVT_PEEK
);
311 wxSocketBase
& wxSocketBase::Write(const char *buffer
, size_t nbytes
)
313 WantBuffer((char *)buffer
, nbytes
, EVT_WRITE
);
317 wxSocketBase
& wxSocketBase::ReadMsg(char* buffer
, size_t nbytes
)
320 size_t len
, len2
, sig
;
322 Read((char *)&msg
, sizeof(msg
));
323 if (m_lcount
!= sizeof(msg
))
326 sig
= msg
.sig
[0] & 0xff;
327 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
328 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
329 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
331 if (sig
!= 0xfeeddead)
333 len
= msg
.len
[0] & 0xff;
334 len
|= (size_t)(msg
.len
[1] & 0xff) << 8;
335 len
|= (size_t)(msg
.len
[2] & 0xff) << 16;
336 len
|= (size_t)(msg
.len
[3] & 0xff) << 24;
343 if (Read(buffer
, len
).LastCount() != len
)
345 if (len2
&& (Read(NULL
, len2
).LastCount() != len2
))
347 if (Read((char *)&msg
, sizeof(msg
)).LastCount() != sizeof(msg
))
350 sig
= msg
.sig
[0] & 0xff;
351 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
352 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
353 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
355 if (sig
!= 0xdeadfeed)
361 wxSocketBase
& wxSocketBase::WriteMsg(const char *buffer
, size_t nbytes
)
370 msg
.len
[0] = nbytes
& 0xff;
371 msg
.len
[1] = (nbytes
>> 8) & 0xff;
372 msg
.len
[2] = (nbytes
>> 16) & 0xff;
373 msg
.len
[3] = (nbytes
>> 24) & 0xff;
375 if (Write((char *)&msg
, sizeof(msg
)).LastCount() < sizeof(msg
))
377 if (Write(buffer
, nbytes
).LastCount() < nbytes
)
384 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = 0;
385 Write((char *)&msg
, sizeof(msg
));
390 wxSocketBase
& wxSocketBase::Unread(const char *buffer
, size_t nbytes
)
392 CreatePushbackAfter(buffer
, nbytes
);
396 bool wxSocketBase::IsData() const
409 FD_SET(m_fd
, &sock_set
);
410 select(FD_SETSIZE
, &sock_set
, NULL
, NULL
, &tv
);
411 return FD_ISSET(m_fd
, &sock_set
);
414 // ---------------------------------------------------------------------
415 // --------- wxSocketBase Discard(): deletes all byte in the input queue
416 // ---------------------------------------------------------------------
417 void wxSocketBase::Discard()
419 #define MAX_BUFSIZE (10*1024)
420 char *my_data
= new char[MAX_BUFSIZE
];
421 size_t recv_size
= MAX_BUFSIZE
;
424 SetFlags((wxSockFlags
)(NOWAIT
| SPEED
));
426 while (recv_size
== MAX_BUFSIZE
) {
427 recv_size
= Read(my_data
, MAX_BUFSIZE
).LastCount();
436 // --------------------------------------------------------------
437 // --------- wxSocketBase socket info functions -----------------
438 // --------------------------------------------------------------
439 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
441 struct sockaddr my_addr
;
442 size_t len_addr
= sizeof(my_addr
);
448 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, (int *)&len_addr
) < 0)
450 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, (unsigned int *)&len_addr
) < 0)
454 addr_man
.Disassemble(&my_addr
, len_addr
);
458 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
460 struct sockaddr my_addr
;
461 size_t len_addr
= sizeof(my_addr
);
467 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, (int *)&len_addr
) < 0)
469 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, (unsigned int *)&len_addr
) < 0)
473 addr_man
.Disassemble(&my_addr
, len_addr
);
477 // --------------------------------------------------------------
478 // --------- wxSocketBase wait functions ------------------------
479 // --------------------------------------------------------------
480 void wxSocketBase::SaveState()
482 wxSockState
*state
= new wxSockState
;
484 state
->cbk_on
= m_cbkon
;
485 state
->cbk_set
= m_neededreq
;
487 state
->cdata
= m_cdata
;
488 state
->flags
= m_flags
;
489 state
->notif
= m_notifyme
;
491 m_states
.Append(state
);
494 void wxSocketBase::RestoreState()
498 node
= m_states
.Last();
502 wxSockState
*state
= (wxSockState
*)node
->Data();
504 SetFlags(state
->flags
);
505 m_neededreq
= state
->cbk_set
;
507 m_cdata
= state
->cdata
;
508 m_notifyme
= state
->notif
;
518 // --------------------------------------------------------------
519 // --------- wxSocketBase wait functions ------------------------
520 // --------------------------------------------------------------
522 bool wxSocketBase::_Wait(long seconds
, long microseconds
, int type
)
524 if ((!m_connected
&& !m_connecting
) || m_fd
< 0)
527 wxSockWakeUp
wakeup(this, &m_waitflags
, 0);
530 SetNotify((wxRequestNotify
)type
);
534 wakeup
.Start((int)(seconds
*1000 + (microseconds
/ 1000)), TRUE
);
536 m_waitflags
= 0x80 | type
;
537 while (m_waitflags
& 0x80)
542 if (m_waitflags
& 0x40) {
551 bool wxSocketBase::Wait(long seconds
, long microseconds
)
553 return _Wait(seconds
, microseconds
, REQ_ACCEPT
| REQ_CONNECT
|
554 REQ_READ
| REQ_WRITE
| REQ_LOST
);
557 bool wxSocketBase::WaitForRead(long seconds
, long microseconds
)
559 return _Wait(seconds
, microseconds
, REQ_READ
| REQ_LOST
);
562 bool wxSocketBase::WaitForWrite(long seconds
, long microseconds
)
564 return _Wait(seconds
, microseconds
, REQ_WRITE
);
567 bool wxSocketBase::WaitForLost(long seconds
, long microseconds
)
569 return _Wait(seconds
, microseconds
, REQ_LOST
);
572 // --------------------------------------------------------------
573 // --------- wxSocketBase callback management -------------------
574 // --------------------------------------------------------------
576 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
577 #if defined(__WXMOTIF__) || defined(__WXXT__)
578 static void wx_socket_read(XtPointer client
, int *fid
,
579 XtInputId
*WXUNUSED(id
))
582 static void wx_socket_read(gpointer client
, gint fd
,
583 GdkInputCondition
WXUNUSED(cond
))
587 wxSocketBase
*sock
= (wxSocketBase
*)client
;
591 i
= recv(fd
, &c
, 1, MSG_PEEK
);
593 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
)) {
594 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
599 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
602 sock
->OnRequest(wxSocketBase::EVT_READ
);
604 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
)) {
609 sock
->OnRequest(wxSocketBase::EVT_LOST
);
614 #if defined(__WXMOTIF__) || defined(__WXXT__)
615 static void wx_socket_write(XtPointer client
, int *WXUNUSED(fid
),
616 XtInputId
*WXUNUSED(id
))
618 static void wx_socket_write(gpointer client
, gint
WXUNUSED(fd
),
619 GdkInputCondition
WXUNUSED(cond
))
622 wxSocketBase
*sock
= (wxSocketBase
*)client
;
624 if (!sock
->IsConnected())
625 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
627 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
632 Notify_value
wx_sock_read_xview (Notify_client client
, int fd
)
634 wxSocketBase
*sock
= (wxSocketBase
*)client
;
638 i
= recv(fd
, &c
, 1, MSG_PEEK
);
640 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
)) {
641 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
647 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
648 return (Notify_value
) FALSE
;
650 sock
->OnRequest(wxSocketBase::EVT_READ
);
652 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
655 sock
->OnRequest(wxSocketBase::EVT_LOST
);
658 return (Notify_value
) FALSE
;
661 Notify_value
wx_sock_write_xview (Notify_client client
, int fd
)
663 wxSocketBase
*sock
= (wxSocketBase
*)client
;
665 if (!sock
->IsConnected())
666 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
668 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
670 return (Notify_value
) TRUE
;
674 wxSocketBase::wxRequestNotify
wxSocketBase::EventToNotify(wxRequestEvent evt
)
693 void wxSocketBase::SetFlags(wxSockFlags _flags
)
696 if (_flags
& SPEED
) {
697 unsigned long flag
= 0;
698 ioctl(m_fd
, FIONBIO
, &flag
);
700 // SPEED and WAITALL are antagonists.
701 m_flags
= (wxSockFlags
)(m_flags
& ~WAITALL
);
705 unsigned long flag
= 1;
706 ioctl(m_fd
, FIONBIO
, &flag
);
710 void wxSocketBase::SetNotify(wxRequestNotify flags
)
712 wxRequestNotify old_needed_req
= m_neededreq
;
713 if (flags
& REQ_ACCEPT
) {
714 /* Check if server */
715 if (!(GetClassInfo()->IsKindOf(CLASSINFO(wxSocketServer
))))
716 flags
&= ~REQ_ACCEPT
;
719 if (m_cbkon
&& old_needed_req
!= flags
)
723 void wxSocketBase::SetupCallbacks()
725 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| (m_flags
& SPEED
))
728 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
731 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
)) {
733 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_READ
,
734 wx_socket_read
, (gpointer
)this);
736 m_internal
->sock_inputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
737 (XtPointer
*) XtInputReadMask
,
738 (XtInputCallbackProc
) wx_socket_read
,
742 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
)) {
744 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_WRITE
,
745 wx_socket_write
, (gpointer
)this);
747 m_internal
->sock_outputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
748 (XtPointer
*) XtInputWriteMask
,
749 (XtInputCallbackProc
) wx_socket_write
,
757 if (m_neededreq
& REQ_READ
)
759 if (m_neededreq
& REQ_WRITE
)
761 if (m_neededreq
& REQ_LOST
)
763 if (m_neededreq
& REQ_ACCEPT
)
765 if (m_neededreq
& REQ_CONNECT
)
768 if (!m_internal
->my_msg
)
769 m_internal
->my_msg
= m_handler
->NewMessage(this);
770 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), m_internal
->my_msg
, mask
);
773 m_processing
= FALSE
;
776 void wxSocketBase::DestroyCallbacks()
778 if (!m_cbkon
|| !m_handler
)
781 m_processing
= FALSE
;
782 #if defined(__WXMOTIF__) || defined(__WXXT__)
783 if (m_internal
->sock_inputid
> 0)
784 XtRemoveInput(m_internal
->sock_inputid
);
785 m_internal
->sock_inputid
= 0;
786 if (m_internal
->sock_outputid
> 0)
787 XtRemoveInput(m_internal
->sock_outputid
);
788 m_internal
->sock_outputid
= 0;
791 if (m_internal
->sock_inputid
> 0)
792 gdk_input_remove(m_internal
->sock_inputid
);
793 m_internal
->sock_inputid
= 0;
794 if (m_internal
->sock_outputid
> 0)
795 gdk_input_remove(m_internal
->sock_outputid
);
796 m_internal
->sock_outputid
= 0;
799 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), 0, 0);
803 void wxSocketBase::Notify(bool notify
)
805 if (m_notifyme
== notify
)
814 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
816 wxRequestNotify req_notif
= EventToNotify(req_evt
);
818 // Mask the current event
819 SetNotify(m_neededreq
& ~req_notif
);
821 if (req_evt
<= EVT_WRITE
&& DoRequests(req_evt
))
824 if (m_waitflags
& 0xF0) {
826 if ((m_waitflags
& 0x0F) == req_evt
) {
829 DestroyCallbacks(); // I disable it to prevent infinite loop on X11.
835 if (req_evt
== EVT_LOST
) {
840 OldOnNotify(req_evt
);
843 SetNotify(m_neededreq
| req_notif
);
846 wxSocketEvent::wxSocketEvent(int id
)
849 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
854 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
856 wxSocketEvent
event(m_id
);
858 event
.SetEventObject(this);
863 m_cbk(*this, evt
, m_cdata
);
866 // --------------------------------------------------------------
867 // --------- wxSocketBase functions [Callback, CallbackData] ----
868 // --------------------------------------------------------------
869 wxSocketBase::wxSockCbk
wxSocketBase::Callback(wxSocketBase::wxSockCbk _cbk
)
871 wxSockCbk old_cbk
= m_cbk
;
877 char *wxSocketBase::CallbackData(char *cdata_
)
879 char *old_cdata
= m_cdata
;
885 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
887 SetNextHandler(&h_evt
);
891 // --------------------------------------------------------------
892 // --------- wxSocketBase pushback library ----------------------
893 // --------------------------------------------------------------
894 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
898 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
899 curr_pos
= m_unread
+ m_unrd_size
;
901 memcpy(curr_pos
, buffer
, size
);
905 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
907 char *curr_pos
, *new_buf
;
909 new_buf
= (char *) malloc(m_unrd_size
+size
);
910 curr_pos
= new_buf
+ size
;
912 memcpy(new_buf
, buffer
, size
);
913 memcpy(curr_pos
, m_unread
, m_unrd_size
);
920 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
925 if (size
> m_unrd_size
)
927 memcpy(buffer
, m_unread
, size
);
940 // --------------------------------------------------------------
941 // --------- wxSocketBase "multi-thread" core -------------------
942 // --------------------------------------------------------------
944 bool wxSocketBase::DoRequests(wxRequestEvent req_flag
)
946 wxNode
*node
= req_list
[req_flag
].First();
953 SockRequest
*req
= (SockRequest
*)node
->Data();
960 ret
= recv(m_fd
, req
->buffer
, req
->size
,
961 (req
->type
== EVT_PEEK
) ? MSG_PEEK
: 0);
968 if ((len
< req
->size
) && (m_flags
& WAITALL
)) {
972 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
973 req_list
[req_flag
].Insert(req
);
983 ret
= send(m_fd
, req
->buffer
, req
->size
, 0);
990 if ((len
< req
->size
) && (m_flags
& WAITALL
)) {
994 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
995 req_list
[req_flag
].Insert(req
);
1010 void wxSocketBase::WantSpeedBuffer(char *buffer
, size_t nbytes
,
1018 ret
= read(m_fd
, buffer
, nbytes
);
1021 ret
= write(m_fd
, buffer
, nbytes
);
1031 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
1036 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
1039 if (m_flags
& SPEED
) {
1040 WantSpeedBuffer(buffer
, nbytes
, evt
);
1044 SockRequest
*buf
= new SockRequest
;
1045 wxSockWakeUp
s_wake(NULL
, (int *)&buf_timed_out
, (int)TRUE
);
1048 req_list
[evt
].Append(buf
);
1051 SetNotify(REQ_LOST
| EventToNotify(evt
));
1053 buf
->buffer
= buffer
;
1058 buf
->auto_wakeup
= &s_wake
;
1060 buf_timed_out
= FALSE
;
1062 s_wake
.Start(m_timeout
*1000, TRUE
);
1063 if (m_flags
& NOWAIT
) {
1066 while (!buf
->done
&& !buf_timed_out
)
1070 m_lcount
= buf
->nbytes
;
1072 m_error
= ETIMEDOUT
;
1074 m_error
= buf
->error
;
1080 // --------------------------------------------------------------
1081 // wxSocketServer ///////////////////////////////////////////////
1082 // --------------------------------------------------------------
1084 // --------------------------------------------------------------
1085 // --------- wxSocketServer CONSTRUCTOR -------------------------
1086 // --------------------------------------------------------------
1087 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1088 wxSockFlags flags
) :
1089 wxSocketBase(flags
, SOCK_SERVER
)
1091 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1093 if (m_fd
== INVALID_SOCKET
)
1097 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
1099 struct sockaddr
*myaddr
;
1102 addr_man
.Build(myaddr
, len
);
1103 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
1106 if (listen(m_fd
, 5) < 0) {
1107 m_fd
= INVALID_SOCKET
;
1112 // --------------------------------------------------------------
1113 // --------- wxSocketServer Accept ------------------------------
1114 // --------------------------------------------------------------
1115 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
1119 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
1122 struct linger linger
;
1124 linger
.l_linger
= 1;
1126 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1129 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1131 if (!(sock
.m_flags
& SPEED
)) {
1132 unsigned long flag2
= 1;
1133 ioctl(fd2
, FIONBIO
, &flag2
);
1136 sock
.m_type
= SOCK_INTERNAL
;
1138 sock
.m_connected
= TRUE
;
1143 wxSocketBase
*wxSocketServer::Accept()
1145 wxSocketBase
* sock
= new wxSocketBase();
1147 sock
->SetFlags((wxSockFlags
)m_flags
);
1149 if (!AcceptWith(*sock
))
1153 m_handler
->Register(sock
);
1158 // --------------------------------------------------------------
1159 // --------- wxSocketServer callbacks ---------------------------
1160 // --------------------------------------------------------------
1161 void wxSocketServer::OnRequest(wxRequestEvent evt
)
1163 if (evt
== EVT_ACCEPT
) {
1164 OldOnNotify(EVT_ACCEPT
);
1168 // --------------------------------------------------------------
1169 // wxSocketClient ///////////////////////////////////////////////
1170 // --------------------------------------------------------------
1172 // --------- wxSocketClient CONSTRUCTOR -------------------------
1173 // --------------------------------------------------------------
1174 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
1175 wxSocketBase(_flags
, SOCK_CLIENT
)
1179 // --------------------------------------------------------------
1180 // --------- wxSocketClient DESTRUCTOR --------------------------
1181 // --------------------------------------------------------------
1182 wxSocketClient::~wxSocketClient()
1186 // --------------------------------------------------------------
1187 // --------- wxSocketClient Connect functions -------------------
1188 // --------------------------------------------------------------
1189 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool wait
)
1191 struct linger linger
;
1196 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1201 m_connected
= FALSE
;
1204 linger
.l_linger
= 5;
1205 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1207 // Stay in touch with the state of things...
1209 unsigned long flag
= 1;
1210 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1212 // Disable the nagle algorithm, which delays sends till the
1213 // buffer is full (or a certain time period has passed?)...
1215 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1217 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
1220 struct sockaddr
*remote
;
1223 addr_man
.Build(remote
, len
);
1225 if (connect(m_fd
, remote
, len
) != 0)
1228 if (!(m_flags
& SPEED
)) {
1230 ioctl(m_fd
, FIONBIO
, &flag
);
1239 bool wxSocketClient::WaitOnConnect(long seconds
)
1241 int ret
= _Wait(seconds
, 0, REQ_CONNECT
| REQ_LOST
);
1249 void wxSocketClient::OnRequest(wxRequestEvent evt
)
1251 if (evt
== EVT_CONNECT
) {
1253 SetNotify(m_neededreq
& ~REQ_CONNECT
);
1258 OldOnNotify(EVT_CONNECT
);
1262 wxSocketBase::OnRequest(evt
);
1265 /////////////////////////////////////////////////////////////////
1266 // wxSocketHandler ///////////////////////////////////////////////
1267 /////////////////////////////////////////////////////////////////
1269 wxSocketHandler
*wxSocketHandler::master
= NULL
;
1270 #if defined(__WINDOWS__)
1271 static int win_initialized
= 0;
1274 // --------------------------------------------------------------
1275 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1276 // --------------------------------------------------------------
1279 extern char wxPanelClassName
[];
1281 LRESULT APIENTRY _EXPORT
wxSocketHandlerWndProc(HWND hWnd
, UINT message
,
1282 WPARAM wParam
, LPARAM lParam
)
1284 wxSocketHandler
*h_sock
= (wxSocketHandler
*)GetWindowLong(hWnd
, GWL_USERDATA
);
1285 wxNode
*node
= h_sock
->smsg_list
->Find(message
);
1287 wxSocketBase::wxRequestEvent sk_req
;
1288 UINT event
= WSAGETSELECTEVENT(lParam
);
1291 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1293 sock
= (wxSocketBase
*)node
->Data();
1297 sk_req
= wxSocketBase::EVT_READ
;
1300 sk_req
= wxSocketBase::EVT_WRITE
;
1303 sk_req
= wxSocketBase::EVT_LOST
;
1306 sk_req
= wxSocketBase::EVT_ACCEPT
;
1309 sk_req
= wxSocketBase::EVT_CONNECT
;
1312 sock
->OnRequest(sk_req
);
1317 FARPROC wxSocketSubClassProc
= NULL
;
1321 wxSocketHandler::wxSocketHandler()
1323 #if defined(__WINDOWS__)
1324 if (!win_initialized
) {
1327 WSAStartup((1 << 8) | 1, &wsaData
);
1328 win_initialized
= 1;
1330 internal
= new wxSockHandlerInternal
;
1331 internal
->sockWin
= ::CreateWindow(wxPanelClassName
, NULL
, 0,
1332 0, 0, 0, 0, NULL
, (HMENU
) NULL
,
1335 // Subclass the window
1336 if (!wxSocketSubClassProc
)
1337 wxSocketSubClassProc
= MakeProcInstance((FARPROC
) wxSocketHandlerWndProc
, wxhInstance
);
1338 ::SetWindowLong(internal
->sockWin
, GWL_WNDPROC
, (LONG
) wxSocketSubClassProc
);
1339 ::SetWindowLong(internal
->sockWin
, GWL_USERDATA
, (LONG
) this);
1341 internal
->firstAvailableMsg
= 5000;
1342 smsg_list
= new wxList(wxKEY_INTEGER
);
1348 signal(SIGPIPE
, SIG_IGN
);
1352 // --------------------------------------------------------------
1353 // --------- wxSocketHandler DESTRUCTOR -------------------------
1354 // --------------------------------------------------------------
1355 wxSocketHandler::~wxSocketHandler()
1357 wxNode
*next_node
, *node
= socks
->First();
1360 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
1363 next_node
= node
->Next();
1373 ::DestroyWindow(internal
->sockWin
);
1375 win_initialized
= 0;
1381 // --------------------------------------------------------------
1382 // --------- wxSocketHandler registering functions --------------
1383 // --------------------------------------------------------------
1384 void wxSocketHandler::Register(wxSocketBase
* sock
)
1388 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next()) {
1389 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1396 socks
->Append(sock
);
1397 sock
->SetHandler(this);
1398 sock
->SetupCallbacks();
1402 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
1406 for (node
= socks
->First(); node
; node
= node
->Next()) {
1407 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1411 sock
->DestroyCallbacks();
1412 sock
->SetHandler(NULL
);
1418 unsigned long wxSocketHandler::Count() const
1420 return socks
->Number();
1423 // --------------------------------------------------------------
1424 // --------- wxSocketHandler "big" wait functions ---------------
1425 // --------------------------------------------------------------
1426 void handler_cbk(wxSocketBase
& sock
,
1427 wxSocketBase::wxRequestEvent
WXUNUSED(flags
),
1430 int *a_wait
= (int *)cdata
;
1436 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1440 wxSockWakeUp
s_wake(NULL
, &on_wait
, -2);
1443 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1444 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1448 sock
->SetupCallbacks();
1450 sock
->Callback(handler_cbk
);
1451 sock
->CallbackData((char *)&on_wait
);
1455 s_wake
.Start((seconds
*1000) + (microseconds
/1000), TRUE
);
1460 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1461 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1463 sock
->RestoreState();
1472 void wxSocketHandler::YieldSock()
1476 for (node
= socks
->First(); node
; node
= node
->Next() ) {
1477 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1481 sock
->SetFlags(wxSocketBase::SPEED
);
1483 sock
->DoRequests(wxSocketBase::EVT_READ
);
1484 sock
->DoRequests(wxSocketBase::EVT_WRITE
);
1486 sock
->RestoreState();
1490 // --------------------------------------------------------------
1491 // --------- wxSocketHandler: create and register the socket ----
1492 // --------------------------------------------------------------
1493 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1494 wxSocketBase::wxSockFlags flags
)
1496 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1502 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1504 wxSocketClient
*client
= new wxSocketClient(flags
);
1511 // --------------------------------------------------------------
1512 // --------- wxSocketHandler: Windows specific methods ----------
1513 // --------------------------------------------------------------
1514 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1516 internal
->firstAvailableMsg
++;
1517 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1518 return internal
->firstAvailableMsg
;
1521 void wxSocketHandler::DestroyMessage(UINT msg
)
1523 wxNode
*node
= smsg_list
->Find(msg
);
1527 HWND
wxSocketHandler::GetHWND() const
1529 return internal
->sockWin
;