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>
66 #if defined(__WXMOTIF__) || defined(__WXXT__)
67 #include <X11/Intrinsic.h>
69 /////////////////////////////
70 // Needs internal variables
71 /////////////////////////////
73 #define Uses_XtIntrinsic
78 #if defined(__WXGTK__)
82 /////////////////////////////////////////////////////////////////////////////
84 /////////////////////////////////////////////////////////////////////////////
85 #define WXSOCK_INTERNAL
86 #include "wx/sckaddr.h"
87 #include "wx/socket.h"
89 /////////////////////////////////////////////////////////////////////////////
90 // Some patch ///// BEGIN
91 /////////////////////////////////////////////////////////////////////////////
93 #define close closesocket
94 #define ioctl ioctlsocket
95 #define errno WSAGetLastError()
99 #define EWOULDBLOCK WSAEWOULDBLOCK
100 #define ETIMEDOUT WSAETIMEDOUT
102 #define EINTR WSAEINTR
106 #define INVALID_SOCKET -1
110 #define wxAPP_CONTEXT wxTheApp->appContext
114 // This is an MS TCP/IP routine and is not needed here. Some WinSock
115 // implementations (such as PC-NFS) will require you to include this
116 // or a similar routine (see appendix in WinSock doc or help file).
118 #if defined( NEED_WSAFDIsSet ) || defined( _MSC_VER )
119 int PASCAL FAR
__WSAFDIsSet(SOCKET fd
, fd_set FAR
*set
)
121 int i
= set
->fd_count
;
125 if (set
->fd_array
[i
] == fd
)
134 #if defined(__WINDOWS__)
135 #define PROCESS_EVENTS() wxYield()
136 #elif defined(__WXXT__) || defined(__WXMOTIF__)
137 #define PROCESS_EVENTS() XtAppProcessEvent(wxAPP_CONTEXT, XtIMAll)
138 #elif defined(__WXGTK__)
139 #define PROCESS_EVENTS() gtk_main_iteration()
142 /////////////////////////////////////////////////////////////////////////////
143 // Some patch ///// END
144 /////////////////////////////////////////////////////////////////////////////
146 // --------------------------------------------------------------
148 // --------------------------------------------------------------
149 #if !USE_SHARED_LIBRARY
150 IMPLEMENT_CLASS(wxSocketBase
, wxObject
)
151 IMPLEMENT_CLASS(wxSocketServer
, wxSocketBase
)
152 IMPLEMENT_CLASS(wxSocketClient
, wxSocketBase
)
153 IMPLEMENT_CLASS(wxSocketHandler
, wxObject
)
154 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent
, wxEvent
)
157 class wxSockWakeUp
: public wxTimer
{
163 wxSockWakeUp(wxSocketBase
*_sock
, int *id
, int new_val
) {
164 my_id
= id
; n_val
= new_val
;
167 virtual void Notify() {
169 if (sock
) sock
->Notify(FALSE
);
174 class SockRequest
: public wxObject
{
180 wxSockWakeUp
*auto_wakeup
;
181 wxSocketBase::wxRequestNotify type
;
185 /////////////////////////////////////////////////////////////////////////////
186 // Some internal define
187 /////////////////////////////////////////////////////////////////////////////
189 // --------------------------------------------------------------
190 // --------- wxSocketBase CONSTRUCTOR ---------------------------
191 // --------------------------------------------------------------
192 wxSocketBase::wxSocketBase(wxSocketBase::wxSockFlags _flags
,
193 wxSocketBase::wxSockType _type
) :
195 m_flags(_flags
), m_type(_type
), m_connected(FALSE
), m_connecting(FALSE
),
196 m_fd(INVALID_SOCKET
), m_waitflags(0), m_cbk(0), m_cdata(0), m_id(-1),
198 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
200 m_unread(NULL
), m_unrd_size(0),
202 m_timeout(3600), m_wantbuf(0)
204 m_internal
= new wxSockInternal
;
205 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
206 m_internal
->sock_inputid
= 0;
207 m_internal
->sock_outputid
= 0;
208 m_internal
->sock_exceptid
= 0;
211 m_internal
->my_msg
= 0;
215 wxSocketBase::wxSocketBase() :
217 m_flags(WAITALL
), m_type(SOCK_UNINIT
), m_connected(FALSE
),
218 m_connecting(FALSE
), m_fd(INVALID_SOCKET
), m_waitflags(0),
219 m_cbk(0), m_cdata(0),
220 m_id(-1), m_handler(0),
221 m_neededreq((wxRequestNotify
)(REQ_READ
| REQ_LOST
)),
223 m_unread(NULL
), m_unrd_size(0),
225 m_timeout(3600), m_wantbuf(0)
227 m_internal
= new wxSockInternal
;
228 #if defined(__WXXT__) || defined(__WXMOTIF__) || defined(__WXGTK__)
229 m_internal
->sock_inputid
= 0;
230 m_internal
->sock_outputid
= 0;
231 m_internal
->sock_exceptid
= 0;
234 m_internal
->my_msg
= 0;
238 // --------------------------------------------------------------
239 // --------- wxSocketBase CONSTRUCTOR ---------------------------
240 // --------------------------------------------------------------
241 wxSocketBase::~wxSocketBase()
250 if (m_internal
->my_msg
)
251 m_handler
->DestroyMessage(m_internal
->my_msg
);
253 m_handler
->UnRegister(this);
255 m_states
.DeleteContents(TRUE
);
260 bool wxSocketBase::Close()
262 if (m_fd
!= INVALID_SOCKET
) {
263 for (int i
=0;i
<3;i
++) {
264 wxNode
*n
, *node
= req_list
[i
].First();
267 SockRequest
*req
= (SockRequest
*)node
->Data();
279 m_fd
= INVALID_SOCKET
;
286 // --------------------------------------------------------------
287 // --------- wxSocketBase base IO functions ---------------------
288 // --------------------------------------------------------------
289 wxSocketBase
& wxSocketBase::Read(char* buffer
, size_t nbytes
)
291 m_lcount
= GetPushback(buffer
, nbytes
, FALSE
);
293 // If we have got the whole needed buffer or if we don't want to
294 // wait then it returns immediately.
295 if (!nbytes
|| (m_lcount
&& !(m_flags
& WAITALL
)) )
298 WantBuffer(buffer
, nbytes
, EVT_READ
);
303 wxSocketBase
& wxSocketBase::Peek(char* buffer
, size_t nbytes
)
305 size_t nbytes_old
= nbytes
;
307 nbytes
-= GetPushback(buffer
, nbytes
, TRUE
);
309 m_lcount
= nbytes_old
;
313 WantBuffer(buffer
, nbytes
, EVT_PEEK
);
318 wxSocketBase
& wxSocketBase::Write(const char *buffer
, size_t nbytes
)
320 WantBuffer((char *)buffer
, nbytes
, EVT_WRITE
);
324 wxSocketBase
& wxSocketBase::ReadMsg(char* buffer
, size_t nbytes
)
327 size_t len
, len2
, sig
;
329 Read((char *)&msg
, sizeof(msg
));
330 if (m_lcount
!= sizeof(msg
))
333 sig
= msg
.sig
[0] & 0xff;
334 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
335 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
336 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
338 if (sig
!= 0xfeeddead)
340 len
= msg
.len
[0] & 0xff;
341 len
|= (size_t)(msg
.len
[1] & 0xff) << 8;
342 len
|= (size_t)(msg
.len
[2] & 0xff) << 16;
343 len
|= (size_t)(msg
.len
[3] & 0xff) << 24;
350 if (Read(buffer
, len
).LastCount() != len
)
352 if (len2
&& (Read(NULL
, len2
).LastCount() != len2
))
354 if (Read((char *)&msg
, sizeof(msg
)).LastCount() != sizeof(msg
))
357 sig
= msg
.sig
[0] & 0xff;
358 sig
|= (size_t)(msg
.sig
[1] & 0xff) << 8;
359 sig
|= (size_t)(msg
.sig
[2] & 0xff) << 16;
360 sig
|= (size_t)(msg
.sig
[3] & 0xff) << 24;
362 if (sig
!= 0xdeadfeed)
368 wxSocketBase
& wxSocketBase::WriteMsg(const char *buffer
, size_t nbytes
)
377 msg
.len
[0] = nbytes
& 0xff;
378 msg
.len
[1] = (nbytes
>> 8) & 0xff;
379 msg
.len
[2] = (nbytes
>> 16) & 0xff;
380 msg
.len
[3] = (nbytes
>> 24) & 0xff;
382 if (Write((char *)&msg
, sizeof(msg
)).LastCount() < sizeof(msg
))
384 if (Write(buffer
, nbytes
).LastCount() < nbytes
)
391 msg
.len
[0] = msg
.len
[1] = msg
.len
[2] = msg
.len
[3] = 0;
392 Write((char *)&msg
, sizeof(msg
));
397 wxSocketBase
& wxSocketBase::Unread(const char *buffer
, size_t nbytes
)
399 CreatePushbackAfter(buffer
, nbytes
);
403 bool wxSocketBase::IsData() const
416 FD_SET(m_fd
, &sock_set
);
417 select(FD_SETSIZE
, &sock_set
, NULL
, NULL
, &tv
);
418 return FD_ISSET(m_fd
, &sock_set
);
421 // ---------------------------------------------------------------------
422 // --------- wxSocketBase Discard(): deletes all byte in the input queue
423 // ---------------------------------------------------------------------
424 void wxSocketBase::Discard()
426 #define MAX_BUFSIZE (10*1024)
427 char *my_data
= new char[MAX_BUFSIZE
];
428 size_t recv_size
= MAX_BUFSIZE
;
431 SetFlags((wxSockFlags
)(NOWAIT
| SPEED
));
433 while (recv_size
== MAX_BUFSIZE
) {
434 recv_size
= Read(my_data
, MAX_BUFSIZE
).LastCount();
443 // --------------------------------------------------------------
444 // --------- wxSocketBase socket info functions -----------------
445 // --------------------------------------------------------------
446 bool wxSocketBase::GetPeer(wxSockAddress
& addr_man
) const
448 struct sockaddr my_addr
;
449 size_t len_addr
= sizeof(my_addr
);
455 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, (int *)&len_addr
) < 0)
457 if (getpeername(m_fd
, (struct sockaddr
*)&my_addr
, (unsigned int *)&len_addr
) < 0)
461 addr_man
.Disassemble(&my_addr
, len_addr
);
465 bool wxSocketBase::GetLocal(wxSockAddress
& addr_man
) const
467 struct sockaddr my_addr
;
468 size_t len_addr
= sizeof(my_addr
);
474 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, (int *)&len_addr
) < 0)
476 if (getsockname(m_fd
, (struct sockaddr
*)&my_addr
, (unsigned int *)&len_addr
) < 0)
480 addr_man
.Disassemble(&my_addr
, len_addr
);
484 // --------------------------------------------------------------
485 // --------- wxSocketBase wait functions ------------------------
486 // --------------------------------------------------------------
487 void wxSocketBase::SaveState()
489 wxSockState
*state
= new wxSockState
;
491 state
->cbk_on
= m_cbkon
;
492 state
->cbk_set
= m_neededreq
;
494 state
->cdata
= m_cdata
;
495 state
->flags
= m_flags
;
496 state
->notif
= m_notifyme
;
498 m_states
.Append(state
);
501 void wxSocketBase::RestoreState()
505 node
= m_states
.Last();
509 wxSockState
*state
= (wxSockState
*)node
->Data();
511 SetFlags(state
->flags
);
512 m_neededreq
= state
->cbk_set
;
514 m_cdata
= state
->cdata
;
515 m_notifyme
= state
->notif
;
525 // --------------------------------------------------------------
526 // --------- wxSocketBase wait functions ------------------------
527 // --------------------------------------------------------------
529 bool wxSocketBase::_Wait(long seconds
, long microseconds
, int type
)
531 if ((!m_connected
&& !m_connecting
) || m_fd
< 0)
534 wxSockWakeUp
wakeup(this, &m_waitflags
, 0);
537 SetNotify((wxRequestNotify
)type
);
541 wakeup
.Start((int)(seconds
*1000 + (microseconds
/ 1000)), TRUE
);
543 m_waitflags
= 0x80 | type
;
544 while (m_waitflags
& 0x80)
549 if (m_waitflags
& 0x40) {
558 bool wxSocketBase::Wait(long seconds
, long microseconds
)
560 return _Wait(seconds
, microseconds
, REQ_ACCEPT
| REQ_CONNECT
|
561 REQ_READ
| REQ_WRITE
| REQ_LOST
);
564 bool wxSocketBase::WaitForRead(long seconds
, long microseconds
)
566 return _Wait(seconds
, microseconds
, REQ_READ
| REQ_LOST
);
569 bool wxSocketBase::WaitForWrite(long seconds
, long microseconds
)
571 return _Wait(seconds
, microseconds
, REQ_WRITE
);
574 bool wxSocketBase::WaitForLost(long seconds
, long microseconds
)
576 return _Wait(seconds
, microseconds
, REQ_LOST
);
579 // --------------------------------------------------------------
580 // --------- wxSocketBase callback management -------------------
581 // --------------------------------------------------------------
583 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
584 #if defined(__WXMOTIF__) || defined(__WXXT__)
585 static void wx_socket_read(XtPointer client
, int *fid
,
586 XtInputId
*WXUNUSED(id
))
589 static void wx_socket_read(gpointer client
, gint fd
,
590 GdkInputCondition
WXUNUSED(cond
))
594 wxSocketBase
*sock
= (wxSocketBase
*)client
;
598 i
= recv(fd
, &c
, 1, MSG_PEEK
);
600 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
)) {
601 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
606 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
609 sock
->OnRequest(wxSocketBase::EVT_READ
);
611 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
)) {
616 sock
->OnRequest(wxSocketBase::EVT_LOST
);
621 #if defined(__WXMOTIF__) || defined(__WXXT__)
622 static void wx_socket_write(XtPointer client
, int *WXUNUSED(fid
),
623 XtInputId
*WXUNUSED(id
))
625 static void wx_socket_write(gpointer client
, gint
WXUNUSED(fd
),
626 GdkInputCondition
WXUNUSED(cond
))
629 wxSocketBase
*sock
= (wxSocketBase
*)client
;
631 if (!sock
->IsConnected())
632 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
634 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
639 Notify_value
wx_sock_read_xview (Notify_client client
, int fd
)
641 wxSocketBase
*sock
= (wxSocketBase
*)client
;
645 i
= recv(fd
, &c
, 1, MSG_PEEK
);
647 if (i
== -1 && (sock
->NeededReq() & wxSocketBase::REQ_ACCEPT
)) {
648 sock
->OnRequest(wxSocketBase::EVT_ACCEPT
);
654 if (!(sock
->NeededReq() & wxSocketBase::REQ_READ
))
655 return (Notify_value
) FALSE
;
657 sock
->OnRequest(wxSocketBase::EVT_READ
);
659 if (!(sock
->NeededReq() & wxSocketBase::REQ_LOST
))
662 sock
->OnRequest(wxSocketBase::EVT_LOST
);
665 return (Notify_value
) FALSE
;
668 Notify_value
wx_sock_write_xview (Notify_client client
, int fd
)
670 wxSocketBase
*sock
= (wxSocketBase
*)client
;
672 if (!sock
->IsConnected())
673 sock
->OnRequest(wxSocketBase::EVT_CONNECT
);
675 sock
->OnRequest(wxSocketBase::EVT_WRITE
);
677 return (Notify_value
) TRUE
;
681 wxSocketBase::wxRequestNotify
wxSocketBase::EventToNotify(wxRequestEvent evt
)
700 void wxSocketBase::SetFlags(wxSockFlags _flags
)
703 if (_flags
& SPEED
) {
704 unsigned long flag
= 0;
705 ioctl(m_fd
, FIONBIO
, &flag
);
707 // SPEED and WAITALL are antagonists.
708 m_flags
= (wxSockFlags
)(m_flags
& ~WAITALL
);
712 unsigned long flag
= 1;
713 ioctl(m_fd
, FIONBIO
, &flag
);
717 void wxSocketBase::SetNotify(wxRequestNotify flags
)
719 wxRequestNotify old_needed_req
= m_neededreq
;
720 if (flags
& REQ_ACCEPT
) {
721 /* Check if server */
722 if (!(GetClassInfo()->IsKindOf(CLASSINFO(wxSocketServer
))))
723 flags
&= ~REQ_ACCEPT
;
726 if (m_cbkon
&& old_needed_req
!= flags
)
730 void wxSocketBase::SetupCallbacks()
732 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| (m_flags
& SPEED
))
735 #if defined(__WXMOTIF__) || defined(__WXXT__) || defined(__WXGTK__)
738 if (m_neededreq
& (REQ_ACCEPT
| REQ_READ
| REQ_LOST
)) {
740 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_READ
,
741 wx_socket_read
, (gpointer
)this);
743 m_internal
->sock_inputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
744 (XtPointer
*) XtInputReadMask
,
745 (XtInputCallbackProc
) wx_socket_read
,
749 if (m_neededreq
& (REQ_CONNECT
| REQ_WRITE
)) {
751 m_internal
->sock_inputid
= gdk_input_add(m_fd
, GDK_INPUT_WRITE
,
752 wx_socket_write
, (gpointer
)this);
754 m_internal
->sock_outputid
= XtAppAddInput (wxAPP_CONTEXT
, m_fd
,
755 (XtPointer
*) XtInputWriteMask
,
756 (XtInputCallbackProc
) wx_socket_write
,
764 if (m_neededreq
& REQ_READ
)
766 if (m_neededreq
& REQ_WRITE
)
768 if (m_neededreq
& REQ_LOST
)
770 if (m_neededreq
& REQ_ACCEPT
)
772 if (m_neededreq
& REQ_CONNECT
)
775 if (!m_internal
->my_msg
)
776 m_internal
->my_msg
= m_handler
->NewMessage(this);
777 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), m_internal
->my_msg
, mask
);
780 m_processing
= FALSE
;
783 void wxSocketBase::DestroyCallbacks()
785 if (!m_cbkon
|| !m_handler
)
788 m_processing
= FALSE
;
789 #if defined(__WXMOTIF__) || defined(__WXXT__)
790 if (m_internal
->sock_inputid
> 0)
791 XtRemoveInput(m_internal
->sock_inputid
);
792 m_internal
->sock_inputid
= 0;
793 if (m_internal
->sock_outputid
> 0)
794 XtRemoveInput(m_internal
->sock_outputid
);
795 m_internal
->sock_outputid
= 0;
798 if (m_internal
->sock_inputid
> 0)
799 gdk_input_remove(m_internal
->sock_inputid
);
800 m_internal
->sock_inputid
= 0;
801 if (m_internal
->sock_outputid
> 0)
802 gdk_input_remove(m_internal
->sock_outputid
);
803 m_internal
->sock_outputid
= 0;
806 WSAAsyncSelect(m_fd
, m_handler
->GetHWND(), 0, 0);
810 void wxSocketBase::Notify(bool notify
)
812 if (m_notifyme
== notify
)
821 void wxSocketBase::OnRequest(wxRequestEvent req_evt
)
823 wxRequestNotify req_notif
= EventToNotify(req_evt
);
825 // Mask the current event
826 SetNotify(m_neededreq
& ~req_notif
);
828 if (req_evt
<= EVT_WRITE
&& DoRequests(req_evt
))
831 if (m_waitflags
& 0xF0) {
833 if ((m_waitflags
& 0x0F) == req_evt
) {
836 DestroyCallbacks(); // I disable it to prevent infinite loop on X11.
842 if (req_evt
== EVT_LOST
) {
847 OldOnNotify(req_evt
);
850 SetNotify(m_neededreq
| req_notif
);
853 wxSocketEvent::wxSocketEvent(int id
)
856 wxEventType type
= (wxEventType
)wxEVT_SOCKET
;
861 void wxSocketBase::OldOnNotify(wxRequestEvent evt
)
863 wxSocketEvent
event(m_id
);
865 event
.SetEventObject(this);
870 m_cbk(*this, evt
, m_cdata
);
873 // --------------------------------------------------------------
874 // --------- wxSocketBase functions [Callback, CallbackData] ----
875 // --------------------------------------------------------------
876 wxSocketBase::wxSockCbk
wxSocketBase::Callback(wxSocketBase::wxSockCbk _cbk
)
878 wxSockCbk old_cbk
= m_cbk
;
884 char *wxSocketBase::CallbackData(char *cdata_
)
886 char *old_cdata
= m_cdata
;
892 void wxSocketBase::SetEventHandler(wxEvtHandler
& h_evt
, int id
)
894 SetNextHandler(&h_evt
);
898 // --------------------------------------------------------------
899 // --------- wxSocketBase pushback library ----------------------
900 // --------------------------------------------------------------
901 void wxSocketBase::CreatePushbackAfter(const char *buffer
, size_t size
)
905 m_unread
= (char *) realloc(m_unread
, m_unrd_size
+size
);
906 curr_pos
= m_unread
+ m_unrd_size
;
908 memcpy(curr_pos
, buffer
, size
);
912 void wxSocketBase::CreatePushbackBefore(const char *buffer
, size_t size
)
914 char *curr_pos
, *new_buf
;
916 new_buf
= (char *) malloc(m_unrd_size
+size
);
917 curr_pos
= new_buf
+ size
;
919 memcpy(new_buf
, buffer
, size
);
920 memcpy(curr_pos
, m_unread
, m_unrd_size
);
927 size_t wxSocketBase::GetPushback(char *buffer
, size_t size
, bool peek
)
932 if (size
> m_unrd_size
)
934 memcpy(buffer
, m_unread
, size
);
947 // --------------------------------------------------------------
948 // --------- wxSocketBase "multi-thread" core -------------------
949 // --------------------------------------------------------------
951 bool wxSocketBase::DoRequests(wxRequestEvent req_flag
)
953 wxNode
*node
= req_list
[req_flag
].First();
960 SockRequest
*req
= (SockRequest
*)node
->Data();
967 ret
= recv(m_fd
, req
->buffer
, req
->size
,
968 (req
->type
== EVT_PEEK
) ? MSG_PEEK
: 0);
975 if ((len
< req
->size
) && (m_flags
& WAITALL
)) {
979 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
980 req_list
[req_flag
].Insert(req
);
990 ret
= send(m_fd
, req
->buffer
, req
->size
, 0);
997 if ((len
< req
->size
) && (m_flags
& WAITALL
)) {
1001 req
->auto_wakeup
->Start(m_timeout
*1000, TRUE
);
1002 req_list
[req_flag
].Insert(req
);
1017 void wxSocketBase::WantSpeedBuffer(char *buffer
, size_t nbytes
,
1025 ret
= recv(m_fd
, buffer
, nbytes
,
1026 (evt
== EVT_PEEK
) ? MSG_PEEK
: 0);
1029 ret
= send(m_fd
, buffer
, nbytes
, 0);
1039 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
1044 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
1047 if (m_flags
& SPEED
) {
1048 WantSpeedBuffer(buffer
, nbytes
, evt
);
1052 SockRequest
*buf
= new SockRequest
;
1053 wxSockWakeUp
s_wake(NULL
, (int *)&buf_timed_out
, (int)TRUE
);
1056 req_list
[evt
].Append(buf
);
1059 SetNotify(REQ_LOST
| EventToNotify(evt
));
1061 buf
->buffer
= buffer
;
1066 buf
->auto_wakeup
= &s_wake
;
1068 buf_timed_out
= FALSE
;
1070 s_wake
.Start(m_timeout
*1000, TRUE
);
1071 if (m_flags
& NOWAIT
) {
1074 while (!buf
->done
&& !buf_timed_out
)
1078 m_lcount
= buf
->nbytes
;
1080 m_error
= ETIMEDOUT
;
1082 m_error
= buf
->error
;
1088 // --------------------------------------------------------------
1089 // wxSocketServer ///////////////////////////////////////////////
1090 // --------------------------------------------------------------
1092 // --------------------------------------------------------------
1093 // --------- wxSocketServer CONSTRUCTOR -------------------------
1094 // --------------------------------------------------------------
1095 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1096 wxSockFlags flags
) :
1097 wxSocketBase(flags
, SOCK_SERVER
)
1099 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1101 if (m_fd
== INVALID_SOCKET
)
1105 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
1107 struct sockaddr
*myaddr
;
1110 addr_man
.Build(myaddr
, len
);
1111 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
1114 if (listen(m_fd
, 5) < 0) {
1115 m_fd
= INVALID_SOCKET
;
1120 // --------------------------------------------------------------
1121 // --------- wxSocketServer Accept ------------------------------
1122 // --------------------------------------------------------------
1123 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
1127 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
1130 struct linger linger
;
1132 linger
.l_linger
= 1;
1134 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1137 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1139 if (!(sock
.m_flags
& SPEED
)) {
1140 unsigned long flag2
= 1;
1141 ioctl(fd2
, FIONBIO
, &flag2
);
1144 sock
.m_type
= SOCK_INTERNAL
;
1146 sock
.m_connected
= TRUE
;
1151 wxSocketBase
*wxSocketServer::Accept()
1153 wxSocketBase
* sock
= new wxSocketBase();
1155 sock
->SetFlags((wxSockFlags
)m_flags
);
1157 if (!AcceptWith(*sock
))
1161 m_handler
->Register(sock
);
1166 // --------------------------------------------------------------
1167 // --------- wxSocketServer callbacks ---------------------------
1168 // --------------------------------------------------------------
1169 void wxSocketServer::OnRequest(wxRequestEvent evt
)
1171 if (evt
== EVT_ACCEPT
) {
1172 OldOnNotify(EVT_ACCEPT
);
1176 // --------------------------------------------------------------
1177 // wxSocketClient ///////////////////////////////////////////////
1178 // --------------------------------------------------------------
1180 // --------- wxSocketClient CONSTRUCTOR -------------------------
1181 // --------------------------------------------------------------
1182 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
1183 wxSocketBase(_flags
, SOCK_CLIENT
)
1187 // --------------------------------------------------------------
1188 // --------- wxSocketClient DESTRUCTOR --------------------------
1189 // --------------------------------------------------------------
1190 wxSocketClient::~wxSocketClient()
1194 // --------------------------------------------------------------
1195 // --------- wxSocketClient Connect functions -------------------
1196 // --------------------------------------------------------------
1197 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool WXUNUSED(wait
) )
1199 struct linger linger
;
1204 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1209 m_connected
= FALSE
;
1212 linger
.l_linger
= 5;
1213 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1215 // Stay in touch with the state of things...
1217 unsigned long flag
= 1;
1218 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1220 // Disable the nagle algorithm, which delays sends till the
1221 // buffer is full (or a certain time period has passed?)...
1223 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1225 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
1228 struct sockaddr
*remote
;
1231 addr_man
.Build(remote
, len
);
1233 if (connect(m_fd
, remote
, len
) != 0)
1236 if (!(m_flags
& SPEED
)) {
1238 ioctl(m_fd
, FIONBIO
, &flag
);
1247 bool wxSocketClient::WaitOnConnect(long seconds
)
1249 int ret
= _Wait(seconds
, 0, REQ_CONNECT
| REQ_LOST
);
1257 void wxSocketClient::OnRequest(wxRequestEvent evt
)
1259 if (evt
== EVT_CONNECT
) {
1261 SetNotify(m_neededreq
& ~REQ_CONNECT
);
1266 OldOnNotify(EVT_CONNECT
);
1270 wxSocketBase::OnRequest(evt
);
1273 /////////////////////////////////////////////////////////////////
1274 // wxSocketHandler ///////////////////////////////////////////////
1275 /////////////////////////////////////////////////////////////////
1277 wxSocketHandler
*wxSocketHandler::master
= NULL
;
1278 #if defined(__WINDOWS__)
1279 static int win_initialized
= 0;
1282 // --------------------------------------------------------------
1283 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1284 // --------------------------------------------------------------
1287 extern char wxPanelClassName
[];
1289 LRESULT APIENTRY _EXPORT
wxSocketHandlerWndProc(HWND hWnd
, UINT message
,
1290 WPARAM wParam
, LPARAM lParam
)
1292 wxSocketHandler
*h_sock
= (wxSocketHandler
*)GetWindowLong(hWnd
, GWL_USERDATA
);
1293 wxNode
*node
= h_sock
->smsg_list
->Find(message
);
1295 wxSocketBase::wxRequestEvent sk_req
;
1296 UINT event
= WSAGETSELECTEVENT(lParam
);
1299 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1301 sock
= (wxSocketBase
*)node
->Data();
1305 sk_req
= wxSocketBase::EVT_READ
;
1308 sk_req
= wxSocketBase::EVT_WRITE
;
1311 sk_req
= wxSocketBase::EVT_LOST
;
1314 sk_req
= wxSocketBase::EVT_ACCEPT
;
1317 sk_req
= wxSocketBase::EVT_CONNECT
;
1320 sock
->OnRequest(sk_req
);
1325 FARPROC wxSocketSubClassProc
= NULL
;
1329 wxSocketHandler::wxSocketHandler()
1331 #if defined(__WINDOWS__)
1332 if (!win_initialized
) {
1335 WSAStartup((1 << 8) | 1, &wsaData
);
1336 win_initialized
= 1;
1338 internal
= new wxSockHandlerInternal
;
1339 internal
->sockWin
= ::CreateWindow(wxPanelClassName
, NULL
, 0,
1340 0, 0, 0, 0, NULL
, (HMENU
) NULL
,
1343 // Subclass the window
1344 if (!wxSocketSubClassProc
)
1345 wxSocketSubClassProc
= MakeProcInstance((FARPROC
) wxSocketHandlerWndProc
, wxhInstance
);
1346 ::SetWindowLong(internal
->sockWin
, GWL_WNDPROC
, (LONG
) wxSocketSubClassProc
);
1347 ::SetWindowLong(internal
->sockWin
, GWL_USERDATA
, (LONG
) this);
1349 internal
->firstAvailableMsg
= 5000;
1350 smsg_list
= new wxList(wxKEY_INTEGER
);
1356 signal(SIGPIPE
, SIG_IGN
);
1360 // --------------------------------------------------------------
1361 // --------- wxSocketHandler DESTRUCTOR -------------------------
1362 // --------------------------------------------------------------
1363 wxSocketHandler::~wxSocketHandler()
1365 wxNode
*next_node
, *node
= socks
->First();
1368 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
1371 next_node
= node
->Next();
1381 ::DestroyWindow(internal
->sockWin
);
1383 win_initialized
= 0;
1389 // --------------------------------------------------------------
1390 // --------- wxSocketHandler registering functions --------------
1391 // --------------------------------------------------------------
1392 void wxSocketHandler::Register(wxSocketBase
* sock
)
1396 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next()) {
1397 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1404 socks
->Append(sock
);
1405 sock
->SetHandler(this);
1406 sock
->SetupCallbacks();
1410 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
1414 for (node
= socks
->First(); node
; node
= node
->Next()) {
1415 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1419 sock
->DestroyCallbacks();
1420 sock
->SetHandler(NULL
);
1426 unsigned long wxSocketHandler::Count() const
1428 return socks
->Number();
1431 // --------------------------------------------------------------
1432 // --------- wxSocketHandler "big" wait functions ---------------
1433 // --------------------------------------------------------------
1434 void handler_cbk(wxSocketBase
& sock
,
1435 wxSocketBase::wxRequestEvent
WXUNUSED(flags
),
1438 int *a_wait
= (int *)cdata
;
1444 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1448 wxSockWakeUp
s_wake(NULL
, &on_wait
, -2);
1451 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1452 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1456 sock
->SetupCallbacks();
1458 sock
->Callback(handler_cbk
);
1459 sock
->CallbackData((char *)&on_wait
);
1463 s_wake
.Start((seconds
*1000) + (microseconds
/1000), TRUE
);
1468 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1469 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1471 sock
->RestoreState();
1480 void wxSocketHandler::YieldSock()
1484 for (node
= socks
->First(); node
; node
= node
->Next() ) {
1485 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1489 sock
->SetFlags(wxSocketBase::SPEED
);
1491 sock
->DoRequests(wxSocketBase::EVT_READ
);
1492 sock
->DoRequests(wxSocketBase::EVT_WRITE
);
1494 sock
->RestoreState();
1498 // --------------------------------------------------------------
1499 // --------- wxSocketHandler: create and register the socket ----
1500 // --------------------------------------------------------------
1501 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1502 wxSocketBase::wxSockFlags flags
)
1504 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1510 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1512 wxSocketClient
*client
= new wxSocketClient(flags
);
1519 // --------------------------------------------------------------
1520 // --------- wxSocketHandler: Windows specific methods ----------
1521 // --------------------------------------------------------------
1522 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1524 internal
->firstAvailableMsg
++;
1525 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1526 return internal
->firstAvailableMsg
;
1529 void wxSocketHandler::DestroyMessage(UINT msg
)
1531 wxNode
*node
= smsg_list
->Find(msg
);
1535 HWND
wxSocketHandler::GetHWND() const
1537 return internal
->sockWin
;