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
= read(m_fd
, buffer
, nbytes
);
1028 ret
= write(m_fd
, buffer
, nbytes
);
1038 void wxSocketBase::WantBuffer(char *buffer
, size_t nbytes
,
1043 if (m_fd
== INVALID_SOCKET
|| !m_handler
|| !m_connected
)
1046 if (m_flags
& SPEED
) {
1047 WantSpeedBuffer(buffer
, nbytes
, evt
);
1051 SockRequest
*buf
= new SockRequest
;
1052 wxSockWakeUp
s_wake(NULL
, (int *)&buf_timed_out
, (int)TRUE
);
1055 req_list
[evt
].Append(buf
);
1058 SetNotify(REQ_LOST
| EventToNotify(evt
));
1060 buf
->buffer
= buffer
;
1065 buf
->auto_wakeup
= &s_wake
;
1067 buf_timed_out
= FALSE
;
1069 s_wake
.Start(m_timeout
*1000, TRUE
);
1070 if (m_flags
& NOWAIT
) {
1073 while (!buf
->done
&& !buf_timed_out
)
1077 m_lcount
= buf
->nbytes
;
1079 m_error
= ETIMEDOUT
;
1081 m_error
= buf
->error
;
1087 // --------------------------------------------------------------
1088 // wxSocketServer ///////////////////////////////////////////////
1089 // --------------------------------------------------------------
1091 // --------------------------------------------------------------
1092 // --------- wxSocketServer CONSTRUCTOR -------------------------
1093 // --------------------------------------------------------------
1094 wxSocketServer::wxSocketServer(wxSockAddress
& addr_man
,
1095 wxSockFlags flags
) :
1096 wxSocketBase(flags
, SOCK_SERVER
)
1098 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1100 if (m_fd
== INVALID_SOCKET
)
1104 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (char*)&flag
, sizeof(int));
1106 struct sockaddr
*myaddr
;
1109 addr_man
.Build(myaddr
, len
);
1110 if (bind(m_fd
, myaddr
, addr_man
.SockAddrLen()) < 0)
1113 if (listen(m_fd
, 5) < 0) {
1114 m_fd
= INVALID_SOCKET
;
1119 // --------------------------------------------------------------
1120 // --------- wxSocketServer Accept ------------------------------
1121 // --------------------------------------------------------------
1122 bool wxSocketServer::AcceptWith(wxSocketBase
& sock
)
1126 if ((fd2
= accept(m_fd
, 0, 0)) < 0)
1129 struct linger linger
;
1131 linger
.l_linger
= 1;
1133 setsockopt(fd2
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1136 setsockopt(fd2
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1138 if (!(sock
.m_flags
& SPEED
)) {
1139 unsigned long flag2
= 1;
1140 ioctl(fd2
, FIONBIO
, &flag2
);
1143 sock
.m_type
= SOCK_INTERNAL
;
1145 sock
.m_connected
= TRUE
;
1150 wxSocketBase
*wxSocketServer::Accept()
1152 wxSocketBase
* sock
= new wxSocketBase();
1154 sock
->SetFlags((wxSockFlags
)m_flags
);
1156 if (!AcceptWith(*sock
))
1160 m_handler
->Register(sock
);
1165 // --------------------------------------------------------------
1166 // --------- wxSocketServer callbacks ---------------------------
1167 // --------------------------------------------------------------
1168 void wxSocketServer::OnRequest(wxRequestEvent evt
)
1170 if (evt
== EVT_ACCEPT
) {
1171 OldOnNotify(EVT_ACCEPT
);
1175 // --------------------------------------------------------------
1176 // wxSocketClient ///////////////////////////////////////////////
1177 // --------------------------------------------------------------
1179 // --------- wxSocketClient CONSTRUCTOR -------------------------
1180 // --------------------------------------------------------------
1181 wxSocketClient::wxSocketClient(wxSockFlags _flags
) :
1182 wxSocketBase(_flags
, SOCK_CLIENT
)
1186 // --------------------------------------------------------------
1187 // --------- wxSocketClient DESTRUCTOR --------------------------
1188 // --------------------------------------------------------------
1189 wxSocketClient::~wxSocketClient()
1193 // --------------------------------------------------------------
1194 // --------- wxSocketClient Connect functions -------------------
1195 // --------------------------------------------------------------
1196 bool wxSocketClient::Connect(wxSockAddress
& addr_man
, bool wait
)
1198 struct linger linger
;
1203 m_fd
= socket(addr_man
.GetFamily(), SOCK_STREAM
, 0);
1208 m_connected
= FALSE
;
1211 linger
.l_linger
= 5;
1212 setsockopt(m_fd
, SOL_SOCKET
, SO_LINGER
, (char*)&linger
, sizeof(linger
));
1214 // Stay in touch with the state of things...
1216 unsigned long flag
= 1;
1217 setsockopt(m_fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char*)&flag
, sizeof(int));
1219 // Disable the nagle algorithm, which delays sends till the
1220 // buffer is full (or a certain time period has passed?)...
1222 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
1224 setsockopt(m_fd
, IPPROTO_TCP
, TCP_NODELAY
, (char*)&flag
, sizeof(int));
1227 struct sockaddr
*remote
;
1230 addr_man
.Build(remote
, len
);
1232 if (connect(m_fd
, remote
, len
) != 0)
1235 if (!(m_flags
& SPEED
)) {
1237 ioctl(m_fd
, FIONBIO
, &flag
);
1246 bool wxSocketClient::WaitOnConnect(long seconds
)
1248 int ret
= _Wait(seconds
, 0, REQ_CONNECT
| REQ_LOST
);
1256 void wxSocketClient::OnRequest(wxRequestEvent evt
)
1258 if (evt
== EVT_CONNECT
) {
1260 SetNotify(m_neededreq
& ~REQ_CONNECT
);
1265 OldOnNotify(EVT_CONNECT
);
1269 wxSocketBase::OnRequest(evt
);
1272 /////////////////////////////////////////////////////////////////
1273 // wxSocketHandler ///////////////////////////////////////////////
1274 /////////////////////////////////////////////////////////////////
1276 wxSocketHandler
*wxSocketHandler::master
= NULL
;
1277 #if defined(__WINDOWS__)
1278 static int win_initialized
= 0;
1281 // --------------------------------------------------------------
1282 // --------- wxSocketHandler CONSTRUCTOR ------------------------
1283 // --------------------------------------------------------------
1286 extern char wxPanelClassName
[];
1288 LRESULT APIENTRY _EXPORT
wxSocketHandlerWndProc(HWND hWnd
, UINT message
,
1289 WPARAM wParam
, LPARAM lParam
)
1291 wxSocketHandler
*h_sock
= (wxSocketHandler
*)GetWindowLong(hWnd
, GWL_USERDATA
);
1292 wxNode
*node
= h_sock
->smsg_list
->Find(message
);
1294 wxSocketBase::wxRequestEvent sk_req
;
1295 UINT event
= WSAGETSELECTEVENT(lParam
);
1298 return DefWindowProc(hWnd
, message
, wParam
, lParam
);
1300 sock
= (wxSocketBase
*)node
->Data();
1304 sk_req
= wxSocketBase::EVT_READ
;
1307 sk_req
= wxSocketBase::EVT_WRITE
;
1310 sk_req
= wxSocketBase::EVT_LOST
;
1313 sk_req
= wxSocketBase::EVT_ACCEPT
;
1316 sk_req
= wxSocketBase::EVT_CONNECT
;
1319 sock
->OnRequest(sk_req
);
1324 FARPROC wxSocketSubClassProc
= NULL
;
1328 wxSocketHandler::wxSocketHandler()
1330 #if defined(__WINDOWS__)
1331 if (!win_initialized
) {
1334 WSAStartup((1 << 8) | 1, &wsaData
);
1335 win_initialized
= 1;
1337 internal
= new wxSockHandlerInternal
;
1338 internal
->sockWin
= ::CreateWindow(wxPanelClassName
, NULL
, 0,
1339 0, 0, 0, 0, NULL
, (HMENU
) NULL
,
1342 // Subclass the window
1343 if (!wxSocketSubClassProc
)
1344 wxSocketSubClassProc
= MakeProcInstance((FARPROC
) wxSocketHandlerWndProc
, wxhInstance
);
1345 ::SetWindowLong(internal
->sockWin
, GWL_WNDPROC
, (LONG
) wxSocketSubClassProc
);
1346 ::SetWindowLong(internal
->sockWin
, GWL_USERDATA
, (LONG
) this);
1348 internal
->firstAvailableMsg
= 5000;
1349 smsg_list
= new wxList(wxKEY_INTEGER
);
1355 signal(SIGPIPE
, SIG_IGN
);
1359 // --------------------------------------------------------------
1360 // --------- wxSocketHandler DESTRUCTOR -------------------------
1361 // --------------------------------------------------------------
1362 wxSocketHandler::~wxSocketHandler()
1364 wxNode
*next_node
, *node
= socks
->First();
1367 wxSocketBase
* sock
= (wxSocketBase
*)node
->Data();
1370 next_node
= node
->Next();
1380 ::DestroyWindow(internal
->sockWin
);
1382 win_initialized
= 0;
1388 // --------------------------------------------------------------
1389 // --------- wxSocketHandler registering functions --------------
1390 // --------------------------------------------------------------
1391 void wxSocketHandler::Register(wxSocketBase
* sock
)
1395 for (node
= socks
->First(); node
!= NULL
; node
= node
->Next()) {
1396 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1403 socks
->Append(sock
);
1404 sock
->SetHandler(this);
1405 sock
->SetupCallbacks();
1409 void wxSocketHandler::UnRegister(wxSocketBase
* sock
)
1413 for (node
= socks
->First(); node
; node
= node
->Next()) {
1414 wxSocketBase
* s
= (wxSocketBase
*)node
->Data();
1418 sock
->DestroyCallbacks();
1419 sock
->SetHandler(NULL
);
1425 unsigned long wxSocketHandler::Count() const
1427 return socks
->Number();
1430 // --------------------------------------------------------------
1431 // --------- wxSocketHandler "big" wait functions ---------------
1432 // --------------------------------------------------------------
1433 void handler_cbk(wxSocketBase
& sock
,
1434 wxSocketBase::wxRequestEvent
WXUNUSED(flags
),
1437 int *a_wait
= (int *)cdata
;
1443 int wxSocketHandler::Wait(long seconds
, long microseconds
)
1447 wxSockWakeUp
s_wake(NULL
, &on_wait
, -2);
1450 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1451 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1455 sock
->SetupCallbacks();
1457 sock
->Callback(handler_cbk
);
1458 sock
->CallbackData((char *)&on_wait
);
1462 s_wake
.Start((seconds
*1000) + (microseconds
/1000), TRUE
);
1467 for (node
= socks
->First(), i
=0; node
; node
= node
->Next(), i
++) {
1468 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1470 sock
->RestoreState();
1479 void wxSocketHandler::YieldSock()
1483 for (node
= socks
->First(); node
; node
= node
->Next() ) {
1484 wxSocketBase
*sock
= (wxSocketBase
*)node
->Data();
1488 sock
->SetFlags(wxSocketBase::SPEED
);
1490 sock
->DoRequests(wxSocketBase::EVT_READ
);
1491 sock
->DoRequests(wxSocketBase::EVT_WRITE
);
1493 sock
->RestoreState();
1497 // --------------------------------------------------------------
1498 // --------- wxSocketHandler: create and register the socket ----
1499 // --------------------------------------------------------------
1500 wxSocketServer
*wxSocketHandler::CreateServer(wxSockAddress
& addr
,
1501 wxSocketBase::wxSockFlags flags
)
1503 wxSocketServer
*serv
= new wxSocketServer(addr
, flags
);
1509 wxSocketClient
*wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags
)
1511 wxSocketClient
*client
= new wxSocketClient(flags
);
1518 // --------------------------------------------------------------
1519 // --------- wxSocketHandler: Windows specific methods ----------
1520 // --------------------------------------------------------------
1521 UINT
wxSocketHandler::NewMessage(wxSocketBase
*sock
)
1523 internal
->firstAvailableMsg
++;
1524 smsg_list
->Append(internal
->firstAvailableMsg
, sock
);
1525 return internal
->firstAvailableMsg
;
1528 void wxSocketHandler::DestroyMessage(UINT msg
)
1530 wxNode
*node
= smsg_list
->Find(msg
);
1534 HWND
wxSocketHandler::GetHWND() const
1536 return internal
->sockWin
;