]> git.saurik.com Git - wxWidgets.git/blob - src/common/socket.cpp
Fixed SetZoom() so it can be used from the outside.
[wxWidgets.git] / src / common / socket.cpp
1 ////////////////////////////////////////////////////////////////////////////////
2 // Name: socket.cpp
3 // Purpose: Socket handler classes
4 // Authors: Guilhem Lavaux (completely rewritten from a basic API of Andrew
5 // Davidson(1995) in wxWeb)
6 // Created: April 1997
7 // Updated: April 1999
8 // Copyright: (C) 1999 1998, 1997, Guilhem Lavaux
9 // RCS_ID: $Id$
10 // License: see wxWindows license
11 ////////////////////////////////////////////////////////////////////////////////
12 #ifdef __GNUG__
13 #pragma implementation "socket.h"
14 #endif
15
16 #ifdef __MWERKS__
17 typedef int socklen_t ;
18 #endif
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_SOCKETS
28
29 /////////////////////////////////////////////////////////////////////////////
30 // wxWindows headers
31 /////////////////////////////////////////////////////////////////////////////
32 #include <wx/defs.h>
33 #include <wx/object.h>
34 #include <wx/string.h>
35 #include <wx/timer.h>
36 #include <wx/utils.h>
37
38 // Not enough OS behaviour defined for wxStubs
39 #ifndef __WXSTUBS__
40
41 #include <stdlib.h>
42 #include <string.h>
43 #include <ctype.h>
44
45 /////////////////////////////////////////////////////////////////////////////
46 // System specific headers
47 /////////////////////////////////////////////////////////////////////////////
48 #ifdef __WXMAC__
49 // in order to avoid problems with our c library and double definitions
50 #define close closesocket
51 #define ioctl ioctlsocket
52
53 #include <wx/mac/macsock.h>
54
55 #endif
56
57 #if defined(__WINDOWS__)
58 #include <winsock.h>
59 #endif // __WINDOWS__
60
61 #if defined(__UNIX__)
62
63 #ifdef VMS
64 #include <socket.h>
65 #else
66 #include <sys/socket.h>
67 #endif
68 #include <sys/ioctl.h>
69
70 #include <sys/time.h>
71 #include <unistd.h>
72
73 #ifdef sun
74 #include <sys/filio.h>
75 #endif
76
77 #endif // __UNIX__
78
79 #include <signal.h>
80 #include <errno.h>
81
82 #ifdef __VISUALC__
83 #include <io.h>
84 #endif
85
86 /////////////////////////////////////////////////////////////////////////////
87 // wxSocket headers
88 /////////////////////////////////////////////////////////////////////////////
89 #include <wx/module.h>
90 #define WXSOCK_INTERNAL
91 #include <wx/sckaddr.h>
92 #include <wx/socket.h>
93 #include <wx/sckint.h>
94
95 // ----------------------
96 // Some patch ----- BEGIN
97 // ----------------------
98 #ifdef __WINDOWS__
99 #define close closesocket
100 #define ioctl ioctlsocket
101 #ifdef errno
102 #undef errno
103 #endif
104 #define errno WSAGetLastError()
105 #ifdef EWOULDBLOCK
106 #undef EWOULDBLOCK
107 #endif
108 #define EWOULDBLOCK WSAEWOULDBLOCK
109 #define ETIMEDOUT WSAETIMEDOUT
110 #undef EINTR
111 #define EINTR WSAEINTR
112 #endif
113
114 #ifndef __WINDOWS__
115 #define INVALID_SOCKET -1
116 #endif
117
118 #ifdef __WINDOWS__
119 // This is an MS TCP/IP routine and is not needed here. Some WinSock
120 // implementations (such as PC-NFS) will require you to include this
121 // or a similar routine (see appendix in WinSock doc or help file).
122
123 #if defined( NEED_WSAFDIsSet ) || defined( __VISUALC__ )
124 int PASCAL FAR __WSAFDIsSet(SOCKET fd, fd_set FAR *set)
125 {
126 int i = set->fd_count;
127
128 while (i--)
129 {
130 if (set->fd_array[i] == fd)
131 return 1;
132 }
133
134 return 0;
135 }
136 #endif
137 #endif
138
139 // -------------------
140 // Some patch ---- END
141 // -------------------
142
143 #ifdef GetClassInfo
144 #undef GetClassInfo
145 #endif
146
147 // --------------------------------------------------------------
148 // Module
149 // --------------------------------------------------------------
150 class wxSocketModule: public wxModule
151 {
152 DECLARE_DYNAMIC_CLASS(wxSocketModule)
153 public:
154 wxSocketModule() {}
155 bool OnInit();
156 void OnExit();
157 };
158
159 // --------------------------------------------------------------
160 // ClassInfos
161 // --------------------------------------------------------------
162 #if !USE_SHARED_LIBRARY
163 IMPLEMENT_CLASS(wxSocketBase, wxObject)
164 IMPLEMENT_CLASS(wxSocketServer, wxSocketBase)
165 IMPLEMENT_CLASS(wxSocketClient, wxSocketBase)
166 IMPLEMENT_CLASS(wxSocketHandler, wxObject)
167 IMPLEMENT_DYNAMIC_CLASS(wxSocketEvent, wxEvent)
168 IMPLEMENT_DYNAMIC_CLASS(wxSocketModule, wxModule)
169 #endif
170
171 // --------------------------------------------------------------
172 // --------- wxSocketBase CONSTRUCTOR ---------------------------
173 // --------------------------------------------------------------
174 wxSocketBase::wxSocketBase(wxSocketBase::wxSockFlags _flags,
175 wxSocketBase::wxSockType _type) :
176 wxEvtHandler(),
177 m_flags(_flags), m_type(_type), m_connected(FALSE), m_connecting(FALSE),
178 m_fd(INVALID_SOCKET), m_id(-1),
179 m_handler(0),
180 m_neededreq((wxRequestNotify)(REQ_READ | REQ_LOST)),
181 m_timeout(3600),
182 m_unread(NULL), m_unrd_size(0),
183 m_cbk(NULL), m_cdata(NULL),
184 m_notify_state(FALSE)
185 {
186 m_internal = new wxSocketInternal(this);
187 }
188
189 wxSocketBase::wxSocketBase() :
190 wxEvtHandler(),
191 m_flags(WAITALL), m_type(SOCK_UNINIT), m_connected(FALSE),
192 m_connecting(FALSE), m_fd(INVALID_SOCKET),
193 m_id(-1), m_handler(0),
194 m_neededreq((wxRequestNotify)(REQ_READ | REQ_LOST)),
195 m_timeout(3600),
196 m_unread(NULL), m_unrd_size(0),
197 m_cbk(NULL), m_cdata(NULL),
198 m_notify_state(FALSE)
199 {
200 m_internal = new wxSocketInternal(this);
201 }
202
203 // --------------------------------------------------------------
204 // wxSocketBase
205 // --------------------------------------------------------------
206
207 wxSocketBase::~wxSocketBase()
208 {
209 // First, close the file descriptor.
210 Close();
211
212 m_internal->FinalizeSocket();
213
214 if (m_unread)
215 free(m_unread);
216 // Unregister from the handler database.
217 if (m_handler)
218 m_handler->UnRegister(this);
219
220 // Destroy all saved states.
221 m_states.DeleteContents(TRUE);
222
223 // Destroy the socket manager.
224 delete m_internal;
225 }
226
227 bool wxSocketBase::Close()
228 {
229 if (m_fd != INVALID_SOCKET)
230 {
231 // Pause all running socket thread.
232 m_internal->PauseSocket();
233
234 // Shutdown the connection.
235 shutdown(m_fd, 2);
236 close(m_fd);
237 m_fd = INVALID_SOCKET;
238 m_connected = FALSE;
239 }
240
241 return TRUE;
242 }
243
244 // --------------------------------------------------------------
245 // wxSocketBase base IO function
246 // --------------------------------------------------------------
247
248 wxSocketBase& wxSocketBase::Read(char* buffer, size_t nbytes)
249 {
250 m_lcount = GetPushback(buffer, nbytes, FALSE);
251 nbytes -= m_lcount;
252 buffer += m_lcount;
253
254 // If we have got the whole needed buffer or if we don't want to
255 // wait then it returns immediately.
256 if (!nbytes || (m_lcount && !(m_flags & WAITALL)) ) {
257 return *this;
258 }
259
260 WantBuffer(buffer, nbytes, EVT_READ);
261
262 return *this;
263 }
264
265 wxSocketBase& wxSocketBase::Peek(char* buffer, size_t nbytes)
266 {
267 m_lcount = GetPushback(buffer, nbytes, TRUE);
268 if (nbytes-m_lcount == 0)
269 {
270 return *this;
271 }
272 buffer += m_lcount;
273 nbytes -= m_lcount;
274
275 WantBuffer(buffer, nbytes, EVT_PEEK);
276
277 return *this;
278 }
279
280 wxSocketBase& wxSocketBase::Write(const char *buffer, size_t nbytes)
281 {
282 m_lcount = 0;
283 WantBuffer((char *)buffer, nbytes, EVT_WRITE);
284 return *this;
285 }
286
287 wxSocketBase& wxSocketBase::Unread(const char *buffer, size_t nbytes)
288 {
289 CreatePushbackAfter(buffer, nbytes);
290 return *this;
291 }
292
293 bool wxSocketBase::IsData() const
294 {
295 struct timeval tv;
296 fd_set sock_set;
297
298 if (m_fd < 0)
299 return FALSE;
300 if (m_unrd_size > 0)
301 return TRUE;
302
303 m_internal->AcquireFD();
304
305 tv.tv_sec = 0;
306 tv.tv_usec = 0;
307 FD_ZERO(&sock_set);
308 FD_SET(m_fd, &sock_set);
309 select(FD_SETSIZE, &sock_set, NULL, NULL, &tv);
310
311 m_internal->ReleaseFD();
312
313 return (FD_ISSET(m_fd, &sock_set) != 0);
314 }
315
316 // ---------------------------------------------------------------------
317 // --------- wxSocketBase Discard(): deletes all byte in the input queue
318 // ---------------------------------------------------------------------
319 void wxSocketBase::Discard()
320 {
321 #define MAX_BUFSIZE (10*1024)
322 char *my_data = new char[MAX_BUFSIZE];
323 size_t recv_size = MAX_BUFSIZE;
324
325 SaveState();
326 SetFlags((wxSockFlags)(NOWAIT | SPEED));
327
328 while (recv_size == MAX_BUFSIZE)
329 {
330 recv_size = Read(my_data, MAX_BUFSIZE).LastCount();
331 }
332
333 RestoreState();
334 delete [] my_data;
335
336 #undef MAX_BUFSIZE
337 }
338
339 // If what? Who seems to need unsigned int?
340 // BTW uint isn't even defined on wxMSW for VC++ for some reason. Even if it
341 // were, getpeername/getsockname don't take unsigned int*, they take int*.
342 //
343 // Under glibc 2.0.7, socketbits.h declares socklen_t to be unsigned int
344 // and it uses *socklen_t as the 3rd parameter. Robert.
345
346 // JACS - How can we detect this?
347 // Meanwhile, if your compiler complains about socklen_t,
348 // switch lines below.
349
350 #if wxHAVE_GLIBC2
351 # define wxSOCKET_INT socklen_t
352 #else
353 # define wxSOCKET_INT int
354 #endif
355
356 // --------------------------------------------------------------
357 // wxSocketBase socket info functions
358 // --------------------------------------------------------------
359
360 bool wxSocketBase::GetPeer(wxSockAddress& addr_man) const
361 {
362 struct sockaddr my_addr;
363 wxSOCKET_INT len_addr = sizeof(my_addr);
364
365 if (m_fd < 0)
366 return FALSE;
367
368 m_internal->AcquireFD();
369
370 if (getpeername(m_fd, (struct sockaddr *)&my_addr, &len_addr) < 0) {
371 m_internal->ReleaseFD();
372 return FALSE;
373 }
374
375 m_internal->ReleaseFD();
376 addr_man.Disassemble(&my_addr, len_addr);
377 return TRUE;
378 }
379
380 bool wxSocketBase::GetLocal(wxSockAddress& addr_man) const
381 {
382 struct sockaddr my_addr;
383 wxSOCKET_INT len_addr = sizeof(my_addr);
384
385 if (m_fd < 0)
386 return FALSE;
387
388 m_internal->AcquireFD();
389
390 if (getsockname(m_fd, (struct sockaddr *)&my_addr, &len_addr) < 0) {
391 m_internal->ReleaseFD();
392 return FALSE;
393 }
394 m_internal->ReleaseFD();
395
396 addr_man.Disassemble(&my_addr, len_addr);
397 return TRUE;
398 }
399
400 // --------------------------------------------------------------
401 // wxSocketBase wait functions
402 // --------------------------------------------------------------
403
404 void wxSocketBase::SaveState()
405 {
406 SocketState *state = new SocketState;
407
408 state->notify_state = m_notify_state;
409 state->evt_notify_state = m_neededreq;
410 state->socket_flags = m_flags;
411 state->c_callback = m_cbk;
412 state->c_callback_data = m_cdata;
413
414 m_states.Append((wxObject *)state);
415 }
416
417 void wxSocketBase::RestoreState()
418 {
419 wxNode *node;
420 SocketState *state;
421
422 node = m_states.Last();
423 if (!node)
424 return;
425
426 state = (SocketState *)node->Data();
427
428 SetFlags(state->socket_flags);
429 m_neededreq = state->evt_notify_state;
430 m_cbk = state->c_callback;
431 m_cdata = state->c_callback_data;
432 Notify(state->notify_state);
433
434 delete node;
435 delete state;
436 }
437
438 // --------------------------------------------------------------
439 // --------- wxSocketBase callback functions --------------------
440 // --------------------------------------------------------------
441
442 wxSocketBase::wxSockCbk wxSocketBase::Callback(wxSockCbk cbk_)
443 {
444 wxSockCbk old_cbk = cbk_;
445
446 m_cbk = cbk_;
447 return old_cbk;
448 }
449
450 char *wxSocketBase::CallbackData(char *data)
451 {
452 char *old_data = m_cdata;
453
454 m_cdata = data;
455 return old_data;
456 }
457
458 // --------------------------------------------------------------
459 // --------- wxSocketBase wait functions ------------------------
460 // --------------------------------------------------------------
461
462 bool wxSocketBase::_Wait(long seconds, long milliseconds, int type)
463 {
464 SockRequest *req;
465
466 if ((!m_connected && !m_connecting) || m_fd < 0)
467 return FALSE;
468
469 req = new SockRequest;
470
471 req->type = REQ_WAIT | type;
472 req->timeout = seconds * 1000 + milliseconds;
473 req->done = FALSE;
474 req->buffer = NULL;
475 req->size = 0;
476 req->error = 0;
477 req->wait = TRUE;
478 m_internal->QueueRequest(req, TRUE);
479
480 return (req->io_nbytes != 0);
481 }
482
483 bool wxSocketBase::Wait(long seconds, long milliseconds)
484 {
485 return _Wait(seconds, milliseconds, REQ_ACCEPT | REQ_CONNECT |
486 REQ_READ | REQ_WRITE | REQ_LOST);
487 }
488
489 bool wxSocketBase::WaitForRead(long seconds, long milliseconds)
490 {
491 return _Wait(seconds, milliseconds, REQ_READ | REQ_LOST);
492 }
493
494 bool wxSocketBase::WaitForWrite(long seconds, long milliseconds)
495 {
496 return _Wait(seconds, milliseconds, REQ_WRITE);
497 }
498
499 bool wxSocketBase::WaitForLost(long seconds, long milliseconds)
500 {
501 return _Wait(seconds, milliseconds, REQ_LOST);
502 }
503
504 // --------------------------------------------------------------
505 // --------- wxSocketBase callback management -------------------
506 // --------------------------------------------------------------
507
508 wxSocketBase::wxRequestNotify wxSocketBase::EventToNotify(wxRequestEvent evt)
509 {
510 switch (evt)
511 {
512 case EVT_READ:
513 return REQ_READ;
514 case EVT_PEEK:
515 return REQ_PEEK;
516 case EVT_WRITE:
517 return REQ_WRITE;
518 case EVT_LOST:
519 return REQ_LOST;
520 case EVT_ACCEPT:
521 return REQ_ACCEPT;
522 case EVT_CONNECT:
523 return REQ_CONNECT;
524 }
525 return 0;
526 }
527
528 void wxSocketBase::SetFlags(wxSockFlags _flags)
529 {
530 m_flags = _flags;
531 if (_flags & SPEED) {
532 // SPEED and WAITALL are antagonists.
533 m_flags = (wxSockFlags)(m_flags & ~WAITALL);
534 }
535 }
536
537 wxSocketBase::wxSockFlags wxSocketBase::GetFlags() const
538 {
539 return m_flags;
540 }
541
542 void wxSocketBase::SetNotify(wxRequestNotify flags)
543 {
544 /* Check if server */
545 if (m_type != SOCK_SERVER)
546 flags &= ~REQ_ACCEPT;
547
548 m_neededreq = flags;
549 if (m_neededreq == 0)
550 m_internal->DisableWaiter();
551 else
552 Notify(m_notify_state);
553 }
554
555 void wxSocketBase::Notify(bool notify)
556 {
557 m_notify_state = notify;
558 if (m_fd == INVALID_SOCKET)
559 return;
560
561 if (notify)
562 m_internal->EnableWaiter();
563 else
564 m_internal->DisableWaiter();
565 }
566
567 void wxSocketBase::OnRequest(wxRequestEvent req_evt)
568 {
569 wxSocketEvent event(m_id);
570 wxRequestNotify notify = EventToNotify(req_evt);
571
572 if ((m_neededreq & notify) == notify) {
573 event.m_socket = this;
574 event.m_skevt = req_evt;
575 ProcessEvent(event);
576 // TODOTODO
577 // OldOnNotify(req_evt);
578
579 // We disable the event reporting.
580 SetNotify(m_neededreq & ~notify);
581 }
582 }
583
584 wxSocketEvent::wxSocketEvent(int id)
585 : wxEvent(id)
586 {
587 wxEventType type = (wxEventType)wxEVT_SOCKET;
588
589 SetEventType(type);
590 }
591
592 void wxSocketEvent::CopyObject(wxObject& obj_d) const
593 {
594 wxSocketEvent *event = (wxSocketEvent *)&obj_d;
595
596 wxEvent::CopyObject(obj_d);
597
598 event->m_skevt = m_skevt;
599 event->m_socket = m_socket;
600 }
601
602 void wxSocketBase::OldOnNotify(wxRequestEvent evt)
603 {
604 }
605
606 // --------------------------------------------------------------
607 // --------- wxSocketBase functions [Callback, CallbackData] ----
608 // --------------------------------------------------------------
609
610 void wxSocketBase::SetEventHandler(wxEvtHandler& h_evt, int id)
611 {
612 SetNextHandler(&h_evt);
613 m_id = id;
614 }
615
616 // --------------------------------------------------------------
617 // --------- wxSocketBase pushback library ----------------------
618 // --------------------------------------------------------------
619
620 void wxSocketBase::CreatePushbackAfter(const char *buffer, size_t size)
621 {
622 char *curr_pos;
623
624 if (m_unread != NULL)
625 m_unread = (char *) realloc(m_unread, m_unrd_size+size);
626 else
627 m_unread = (char *) malloc(size);
628 curr_pos = m_unread + m_unrd_size;
629
630 memcpy(curr_pos, buffer, size);
631 m_unrd_size += size;
632 }
633
634 void wxSocketBase::CreatePushbackBefore(const char *buffer, size_t size)
635 {
636 char *curr_pos, *new_buf;
637
638 new_buf = (char *) malloc(m_unrd_size+size);
639 curr_pos = new_buf + size;
640
641 memcpy(new_buf, buffer, size);
642 if (m_unrd_size != 0) {
643 memcpy(curr_pos, m_unread, m_unrd_size);
644 free(m_unread);
645 }
646 m_unread = new_buf;
647 m_unrd_size += size;
648 }
649
650 size_t wxSocketBase::GetPushback(char *buffer, size_t size, bool peek)
651 {
652 if (!m_unrd_size)
653 return 0;
654
655 if (size > m_unrd_size)
656 size = m_unrd_size;
657 memcpy(buffer, m_unread, size);
658
659 if (!peek) {
660 m_unrd_size -= size;
661 if (m_unrd_size == 0) {
662 free(m_unread);
663 m_unread = NULL;
664 }
665 }
666
667 return size;
668 }
669
670 // --------------------------------------------------------------
671 // --------- wxSocketBase buffer core requester -----------------
672 // --------------------------------------------------------------
673
674 void wxSocketBase::WantBuffer(char *buffer, size_t nbytes,
675 wxRequestEvent evt)
676 {
677 bool buf_timed_out;
678
679 if (m_fd == INVALID_SOCKET || !m_handler || !m_connected)
680 return;
681
682 SockRequest *buf = new SockRequest;
683
684 SaveState();
685 m_internal->DisableWaiter();
686 buf->buffer = buffer;
687 buf->size = nbytes;
688 buf->done = FALSE;
689 buf->type = EventToNotify(evt);
690 buf->io_nbytes = 0;
691 buf->error = 0;
692 buf->wait = TRUE;
693 buf->timeout = 1000;
694 buf_timed_out = FALSE;
695
696 if (m_flags & SPEED)
697 m_internal->QueueRequest(buf, FALSE);
698 else
699 if (m_flags & NOWAIT)
700 m_internal->QueueRequest(buf, TRUE);
701 else
702 m_internal->QueueRequest(buf, TRUE);
703 m_lcount += buf->io_nbytes;
704 if (buf_timed_out)
705 m_error = ETIMEDOUT;
706 else
707 m_error = buf->error;
708
709 delete buf;
710 RestoreState();
711 }
712
713 // --------------------------------------------------------------
714 // wxSocketServer
715 // --------------------------------------------------------------
716
717 wxSocketServer::wxSocketServer(wxSockAddress& addr_man,
718 wxSockFlags flags) :
719 wxSocketBase(flags, SOCK_SERVER)
720 {
721 m_fd = socket(addr_man.GetFamily(), SOCK_STREAM, 0);
722
723 if (m_fd == INVALID_SOCKET)
724 return;
725
726 int flag = 1;
727 setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&flag, sizeof(int));
728
729 struct sockaddr *myaddr;
730 size_t len;
731
732 addr_man.Build(myaddr, len);
733 if (bind(m_fd, myaddr, addr_man.SockAddrLen()) < 0)
734 return;
735
736 if (listen(m_fd, 5) < 0) {
737 m_fd = INVALID_SOCKET;
738 return;
739 }
740
741 m_internal->InitializeSocket();
742 }
743
744 // --------------------------------------------------------------
745 // wxSocketServer Accept
746 // --------------------------------------------------------------
747
748 bool wxSocketServer::AcceptWith(wxSocketBase& sock)
749 {
750 int fd2;
751
752 m_internal->AcquireFD();
753 if ((fd2 = accept(m_fd, 0, 0)) < 0) {
754 m_internal->ReleaseFD();
755 return FALSE;
756 }
757 m_internal->ReleaseFD();
758
759 struct linger linger;
760 linger.l_onoff = 0;
761 linger.l_linger = 1;
762
763 setsockopt(fd2, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(linger));
764
765 int flag = 0;
766 setsockopt(fd2, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(int));
767
768 sock.m_type = SOCK_INTERNAL;
769 sock.m_fd = fd2;
770 sock.m_connected = TRUE;
771
772 sock.m_internal->InitializeSocket();
773
774 return TRUE;
775 }
776
777 wxSocketBase *wxSocketServer::Accept()
778 {
779 wxSocketBase* sock = new wxSocketBase();
780
781 sock->SetFlags((wxSockFlags)m_flags);
782
783 if (!AcceptWith(*sock))
784 return NULL;
785
786 if (m_handler)
787 m_handler->Register(sock);
788
789 return sock;
790 }
791
792 // --------------------------------------------------------------
793 // wxSocketClient
794 // --------------------------------------------------------------
795
796 // --------- wxSocketClient CONSTRUCTOR -------------------------
797 // --------------------------------------------------------------
798 wxSocketClient::wxSocketClient(wxSockFlags _flags) :
799 wxSocketBase(_flags, SOCK_CLIENT)
800 {
801 }
802
803 // --------------------------------------------------------------
804 // --------- wxSocketClient DESTRUCTOR --------------------------
805 // --------------------------------------------------------------
806 wxSocketClient::~wxSocketClient()
807 {
808 }
809
810 // --------------------------------------------------------------
811 // --------- wxSocketClient Connect functions -------------------
812 // --------------------------------------------------------------
813 bool wxSocketClient::Connect(wxSockAddress& addr_man, bool WXUNUSED(wait) )
814 {
815 struct linger linger;
816
817 if (IsConnected())
818 Close();
819
820 // Initializes all socket stuff ...
821 // --------------------------------
822 m_fd = socket(addr_man.GetFamily(), SOCK_STREAM, 0);
823
824 if (m_fd < 0)
825 return FALSE;
826
827 m_connected = FALSE;
828
829 linger.l_onoff = 1;
830 linger.l_linger = 5;
831 setsockopt(m_fd, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(linger));
832
833 // Stay in touch with the state of things...
834
835 unsigned long flag = 1;
836 setsockopt(m_fd, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(int));
837
838 // Disable the nagle algorithm, which delays sends till the
839 // buffer is full (or a certain time period has passed?)...
840
841 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
842 flag = 1;
843 setsockopt(m_fd, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int));
844 #endif
845
846 struct sockaddr *remote;
847 size_t len;
848
849 addr_man.Build(remote, len);
850
851 if (connect(m_fd, remote, len) != 0)
852 return FALSE;
853
854 // Initializes the background threads ...
855 // --------------------------------------
856 m_internal->InitializeSocket();
857
858 // Enables bg events.
859 // ------------------
860 Notify(TRUE);
861
862 m_connected = TRUE;
863 return TRUE;
864 }
865
866 bool wxSocketClient::WaitOnConnect(long seconds, long microseconds)
867 {
868 int ret = _Wait(seconds, microseconds, REQ_CONNECT | REQ_LOST);
869
870 if (ret)
871 m_connected = TRUE;
872
873 return m_connected;
874 }
875
876 void wxSocketClient::OnRequest(wxRequestEvent evt)
877 {
878 if (evt == EVT_CONNECT)
879 {
880 if (m_connected)
881 {
882 SetNotify(m_neededreq & ~REQ_CONNECT);
883 return;
884 }
885 m_connected = TRUE;
886 OldOnNotify(EVT_CONNECT);
887 return;
888 }
889 wxSocketBase::OnRequest(evt);
890 }
891
892 /////////////////////////////////////////////////////////////////
893 // wxSocketHandler ///////////////////////////////////////////////
894 /////////////////////////////////////////////////////////////////
895
896 wxSocketHandler *wxSocketHandler::master = NULL;
897 #if defined(__WINDOWS__)
898 static int win_initialized = 0;
899 #endif
900
901 // --------------------------------------------------------------
902 // --------- wxSocketHandler CONSTRUCTOR ------------------------
903 // --------------------------------------------------------------
904 wxSocketHandler::wxSocketHandler()
905 {
906 #if defined(__WINDOWS__)
907 if (!win_initialized)
908 {
909 WSADATA wsaData;
910
911 WSAStartup((1 << 8) | 1, &wsaData);
912 win_initialized = 1;
913 }
914 #endif
915
916 socks = new wxList;
917
918 #ifndef __WINDOWS__
919 signal(SIGPIPE, SIG_IGN);
920 #endif
921 }
922
923 // --------------------------------------------------------------
924 // --------- wxSocketHandler DESTRUCTOR -------------------------
925 // --------------------------------------------------------------
926 wxSocketHandler::~wxSocketHandler()
927 {
928 wxNode *next_node, *node = socks->First();
929
930 while (node)
931 {
932 wxSocketBase* sock = (wxSocketBase*)node->Data();
933
934 delete sock;
935 next_node = node->Next();
936 delete node;
937 node = next_node;
938 }
939
940 delete socks;
941
942 #ifdef __WINDOWS__
943 WSACleanup();
944 win_initialized = 0;
945 #endif
946 }
947
948 // --------------------------------------------------------------
949 // --------- wxSocketHandler registering functions --------------
950 // --------------------------------------------------------------
951
952 void wxSocketHandler::Register(wxSocketBase* sock)
953 {
954 wxNode *node;
955
956 for (node = socks->First(); node != NULL; node = node->Next())
957 {
958 wxSocketBase* s = (wxSocketBase*)node->Data();
959
960 if (s == sock)
961 return;
962 }
963
964 if (sock)
965 {
966 socks->Append(sock);
967 sock->SetHandler(this);
968 }
969 }
970
971 void wxSocketHandler::UnRegister(wxSocketBase* sock)
972 {
973 wxNode *node;
974
975 for (node = socks->First(); node; node = node->Next())
976 {
977 wxSocketBase* s = (wxSocketBase*)node->Data();
978
979 if (s == sock)
980 {
981 delete node;
982 sock->SetHandler(NULL);
983 return;
984 }
985 }
986 }
987
988 unsigned long wxSocketHandler::Count() const
989 {
990 return socks->Number();
991 }
992
993 // --------------------------------------------------------------
994 // --------- wxSocketHandler "big" wait functions ---------------
995 // --------------------------------------------------------------
996
997 int wxSocketHandler::Wait(long seconds, long microseconds)
998 {
999 // TODO Needs the completely asynchronous notifier.
1000
1001 /*
1002 int i;
1003 int on_wait;
1004 wxNode *node;
1005 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1006 {
1007 wxSocketBase *sock = (wxSocketBase *)node->Data();
1008
1009 sock->SaveState();
1010
1011 sock->SetupCallbacks();
1012
1013 sock->Callback(handler_cbk);
1014 sock->CallbackData((char *)&on_wait);
1015 }
1016 on_wait = 0;
1017 if (seconds != -1)
1018 s_wake.Start((seconds*1000) + (microseconds/1000), TRUE);
1019
1020 while (!on_wait)
1021 PROCESS_EVENTS();
1022
1023 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1024 {
1025 wxSocketBase *sock = (wxSocketBase *)node->Data();
1026
1027 sock->RestoreState();
1028 }
1029
1030 if (on_wait == -2)
1031 return 0;
1032
1033 return on_wait;
1034 */
1035 return 0;
1036 }
1037
1038 void wxSocketHandler::YieldSock()
1039 {
1040 wxNode *node;
1041
1042 // Nothing to do anymore here except waiting for the queue emptying.
1043 for (node = socks->First(); node; node=node->Next()) {
1044 wxSocketBase *sock = (wxSocketBase *)node->Data();
1045
1046 sock->m_internal->WaitForEnd(NULL);
1047 }
1048 }
1049
1050 // --------------------------------------------------------------
1051 // --------- wxSocketHandler: create and register the socket ----
1052 // --------------------------------------------------------------
1053 wxSocketServer *wxSocketHandler::CreateServer(wxSockAddress& addr,
1054 wxSocketBase::wxSockFlags flags)
1055 {
1056 wxSocketServer *serv = new wxSocketServer(addr, flags);
1057
1058 Register(serv);
1059 return serv;
1060 }
1061
1062 wxSocketClient *wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags)
1063 {
1064 wxSocketClient *client = new wxSocketClient(flags);
1065
1066 Register(client);
1067 return client;
1068 }
1069
1070 bool wxSocketModule::OnInit()
1071 {
1072 wxSocketHandler::master = new wxSocketHandler();
1073 return TRUE;
1074 }
1075
1076 void wxSocketModule::OnExit()
1077 {
1078 delete wxSocketHandler::master;
1079 wxSocketHandler::master = NULL;
1080 }
1081
1082 #endif
1083 // __WXSTUBS__
1084
1085 #endif
1086 // wxUSE_SOCKETS