]> git.saurik.com Git - wxWidgets.git/blob - src/common/socket.cpp
wxFileIn/OutputStream fix
[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 if (m_unread)
213 free(m_unread);
214 // Unregister from the handler database.
215 if (m_handler)
216 m_handler->UnRegister(this);
217
218 // Destroy all saved states.
219 m_states.DeleteContents(TRUE);
220
221 // Destroy the socket manager.
222 delete m_internal;
223 }
224
225 bool wxSocketBase::Close()
226 {
227 if (m_fd != INVALID_SOCKET)
228 {
229 if (m_notify_state == TRUE)
230 Notify(FALSE);
231
232 // Shutdown the connection.
233 shutdown(m_fd, 2);
234 close(m_fd);
235 m_fd = INVALID_SOCKET;
236 m_connected = FALSE;
237 }
238
239 return TRUE;
240 }
241
242 // --------------------------------------------------------------
243 // wxSocketBase base IO function
244 // --------------------------------------------------------------
245
246 wxSocketBase& wxSocketBase::Read(char* buffer, size_t nbytes)
247 {
248 m_lcount = GetPushback(buffer, nbytes, FALSE);
249 nbytes -= m_lcount;
250 buffer += m_lcount;
251
252 // If we have got the whole needed buffer or if we don't want to
253 // wait then it returns immediately.
254 if (!nbytes || (m_lcount && !(m_flags & WAITALL)) ) {
255 return *this;
256 }
257
258 WantBuffer(buffer, nbytes, EVT_READ);
259
260 return *this;
261 }
262
263 wxSocketBase& wxSocketBase::Peek(char* buffer, size_t nbytes)
264 {
265 m_lcount = GetPushback(buffer, nbytes, TRUE);
266 if (nbytes-m_lcount == 0)
267 {
268 return *this;
269 }
270 buffer += m_lcount;
271 nbytes -= m_lcount;
272
273 WantBuffer(buffer, nbytes, EVT_PEEK);
274
275 return *this;
276 }
277
278 wxSocketBase& wxSocketBase::Write(const char *buffer, size_t nbytes)
279 {
280 m_lcount = 0;
281 WantBuffer((char *)buffer, nbytes, EVT_WRITE);
282 return *this;
283 }
284
285 wxSocketBase& wxSocketBase::Unread(const char *buffer, size_t nbytes)
286 {
287 CreatePushbackAfter(buffer, nbytes);
288 return *this;
289 }
290
291 bool wxSocketBase::IsData() const
292 {
293 struct timeval tv;
294 fd_set sock_set;
295
296 if (m_fd < 0)
297 return FALSE;
298 if (m_unrd_size > 0)
299 return TRUE;
300
301 m_internal->AcquireFD();
302
303 tv.tv_sec = 0;
304 tv.tv_usec = 0;
305 FD_ZERO(&sock_set);
306 FD_SET(m_fd, &sock_set);
307 select(FD_SETSIZE, &sock_set, NULL, NULL, &tv);
308
309 m_internal->ReleaseFD();
310
311 return (FD_ISSET(m_fd, &sock_set) != 0);
312 }
313
314 // ---------------------------------------------------------------------
315 // --------- wxSocketBase Discard(): deletes all byte in the input queue
316 // ---------------------------------------------------------------------
317 void wxSocketBase::Discard()
318 {
319 #define MAX_BUFSIZE (10*1024)
320 char *my_data = new char[MAX_BUFSIZE];
321 size_t recv_size = MAX_BUFSIZE;
322
323 SaveState();
324 SetFlags((wxSockFlags)(NOWAIT | SPEED));
325
326 while (recv_size == MAX_BUFSIZE)
327 {
328 recv_size = Read(my_data, MAX_BUFSIZE).LastCount();
329 }
330
331 RestoreState();
332 delete [] my_data;
333
334 #undef MAX_BUFSIZE
335 }
336
337 // If what? Who seems to need unsigned int?
338 // BTW uint isn't even defined on wxMSW for VC++ for some reason. Even if it
339 // were, getpeername/getsockname don't take unsigned int*, they take int*.
340 //
341 // Under glibc 2.0.7, socketbits.h declares socklen_t to be unsigned int
342 // and it uses *socklen_t as the 3rd parameter. Robert.
343
344 // JACS - How can we detect this?
345 // Meanwhile, if your compiler complains about socklen_t,
346 // switch lines below.
347
348 #if wxHAVE_GLIBC2
349 # define wxSOCKET_INT socklen_t
350 #else
351 # define wxSOCKET_INT int
352 #endif
353
354 // --------------------------------------------------------------
355 // wxSocketBase socket info functions
356 // --------------------------------------------------------------
357
358 bool wxSocketBase::GetPeer(wxSockAddress& addr_man) const
359 {
360 struct sockaddr my_addr;
361 wxSOCKET_INT len_addr = sizeof(my_addr);
362
363 if (m_fd < 0)
364 return FALSE;
365
366 m_internal->AcquireFD();
367
368 if (getpeername(m_fd, (struct sockaddr *)&my_addr, &len_addr) < 0) {
369 m_internal->ReleaseFD();
370 return FALSE;
371 }
372
373 m_internal->ReleaseFD();
374 addr_man.Disassemble(&my_addr, len_addr);
375 return TRUE;
376 }
377
378 bool wxSocketBase::GetLocal(wxSockAddress& addr_man) const
379 {
380 struct sockaddr my_addr;
381 wxSOCKET_INT len_addr = sizeof(my_addr);
382
383 if (m_fd < 0)
384 return FALSE;
385
386 m_internal->AcquireFD();
387
388 if (getsockname(m_fd, (struct sockaddr *)&my_addr, &len_addr) < 0) {
389 m_internal->ReleaseFD();
390 return FALSE;
391 }
392 m_internal->ReleaseFD();
393
394 addr_man.Disassemble(&my_addr, len_addr);
395 return TRUE;
396 }
397
398 // --------------------------------------------------------------
399 // wxSocketBase wait functions
400 // --------------------------------------------------------------
401
402 void wxSocketBase::SaveState()
403 {
404 SocketState *state = new SocketState;
405
406 state->notify_state = m_notify_state;
407 state->evt_notify_state = m_neededreq;
408 state->socket_flags = m_flags;
409 state->c_callback = m_cbk;
410 state->c_callback_data = m_cdata;
411
412 m_states.Append((wxObject *)state);
413 }
414
415 void wxSocketBase::RestoreState()
416 {
417 wxNode *node;
418 SocketState *state;
419
420 node = m_states.Last();
421 if (!node)
422 return;
423
424 state = (SocketState *)node->Data();
425
426 SetFlags(state->socket_flags);
427 m_neededreq = state->evt_notify_state;
428 m_cbk = state->c_callback;
429 m_cdata = state->c_callback_data;
430 Notify(state->notify_state);
431
432 delete node;
433 delete state;
434 }
435
436 // --------------------------------------------------------------
437 // --------- wxSocketBase callback functions --------------------
438 // --------------------------------------------------------------
439
440 wxSocketBase::wxSockCbk wxSocketBase::Callback(wxSockCbk cbk_)
441 {
442 wxSockCbk old_cbk = cbk_;
443
444 m_cbk = cbk_;
445 return old_cbk;
446 }
447
448 char *wxSocketBase::CallbackData(char *data)
449 {
450 char *old_data = m_cdata;
451
452 m_cdata = data;
453 return old_data;
454 }
455
456 // --------------------------------------------------------------
457 // --------- wxSocketBase wait functions ------------------------
458 // --------------------------------------------------------------
459
460 bool wxSocketBase::_Wait(long seconds, long milliseconds, int type)
461 {
462 SockRequest *req;
463
464 if ((!m_connected && !m_connecting) || m_fd < 0)
465 return FALSE;
466
467 req = new SockRequest;
468
469 req->type = REQ_WAIT | type;
470 req->timeout = seconds * 1000 + milliseconds;
471 req->done = FALSE;
472 req->buffer = NULL;
473 req->size = 0;
474 req->error = 0;
475 req->wait = TRUE;
476 m_internal->QueueRequest(req, TRUE);
477
478 return (req->io_nbytes != 0);
479 }
480
481 bool wxSocketBase::Wait(long seconds, long milliseconds)
482 {
483 return _Wait(seconds, milliseconds, REQ_ACCEPT | REQ_CONNECT |
484 REQ_READ | REQ_WRITE | REQ_LOST);
485 }
486
487 bool wxSocketBase::WaitForRead(long seconds, long milliseconds)
488 {
489 return _Wait(seconds, milliseconds, REQ_READ | REQ_LOST);
490 }
491
492 bool wxSocketBase::WaitForWrite(long seconds, long milliseconds)
493 {
494 return _Wait(seconds, milliseconds, REQ_WRITE);
495 }
496
497 bool wxSocketBase::WaitForLost(long seconds, long milliseconds)
498 {
499 return _Wait(seconds, milliseconds, REQ_LOST);
500 }
501
502 // --------------------------------------------------------------
503 // --------- wxSocketBase callback management -------------------
504 // --------------------------------------------------------------
505
506 wxSocketBase::wxRequestNotify wxSocketBase::EventToNotify(wxRequestEvent evt)
507 {
508 switch (evt)
509 {
510 case EVT_READ:
511 return REQ_READ;
512 case EVT_PEEK:
513 return REQ_PEEK;
514 case EVT_WRITE:
515 return REQ_WRITE;
516 case EVT_LOST:
517 return REQ_LOST;
518 case EVT_ACCEPT:
519 return REQ_ACCEPT;
520 case EVT_CONNECT:
521 return REQ_CONNECT;
522 }
523 return 0;
524 }
525
526 void wxSocketBase::SetFlags(wxSockFlags _flags)
527 {
528 m_flags = _flags;
529 if (_flags & SPEED) {
530 // SPEED and WAITALL are antagonists.
531 m_flags = (wxSockFlags)(m_flags & ~WAITALL);
532 }
533 }
534
535 wxSocketBase::wxSockFlags wxSocketBase::GetFlags() const
536 {
537 return m_flags;
538 }
539
540 void wxSocketBase::SetNotify(wxRequestNotify flags)
541 {
542 /* Check if server */
543 if (m_type != SOCK_SERVER)
544 flags &= ~REQ_ACCEPT;
545
546 m_internal->AcquireData();
547 m_neededreq = flags;
548 m_internal->ReleaseData();
549 if (m_neededreq == 0)
550 m_internal->StopWaiter();
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->ResumeWaiter();
563 else
564 m_internal->StopWaiter();
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 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->StopWaiter();
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) != 0)
697 m_internal->QueueRequest(buf, FALSE);
698 else
699 if ((m_flags & NOWAIT) != 0)
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->SetFD(m_fd);
742
743 Notify(TRUE);
744 }
745
746 // --------------------------------------------------------------
747 // wxSocketServer Accept
748 // --------------------------------------------------------------
749
750 bool wxSocketServer::AcceptWith(wxSocketBase& sock)
751 {
752 int fd2;
753
754 m_internal->AcquireFD();
755 if ((fd2 = accept(m_fd, 0, 0)) < 0) {
756 m_internal->ReleaseFD();
757 return FALSE;
758 }
759 m_internal->ReleaseFD();
760
761 struct linger linger;
762 linger.l_onoff = 0;
763 linger.l_linger = 1;
764
765 setsockopt(fd2, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(linger));
766
767 int flag = 0;
768 setsockopt(fd2, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(int));
769
770 sock.m_type = SOCK_INTERNAL;
771 sock.m_fd = fd2;
772 sock.m_connected = TRUE;
773
774 sock.m_internal->SetFD(fd2);
775
776 sock.m_internal->ResumeWaiter();
777
778 return TRUE;
779 }
780
781 wxSocketBase *wxSocketServer::Accept()
782 {
783 wxSocketBase* sock = new wxSocketBase();
784
785 sock->SetFlags((wxSockFlags)m_flags);
786
787 if (!AcceptWith(*sock))
788 return NULL;
789
790 if (m_handler)
791 m_handler->Register(sock);
792
793 return sock;
794 }
795
796 // --------------------------------------------------------------
797 // wxSocketClient
798 // --------------------------------------------------------------
799
800 // --------- wxSocketClient CONSTRUCTOR -------------------------
801 // --------------------------------------------------------------
802 wxSocketClient::wxSocketClient(wxSockFlags _flags) :
803 wxSocketBase(_flags, SOCK_CLIENT)
804 {
805 }
806
807 // --------------------------------------------------------------
808 // --------- wxSocketClient DESTRUCTOR --------------------------
809 // --------------------------------------------------------------
810 wxSocketClient::~wxSocketClient()
811 {
812 }
813
814 // --------------------------------------------------------------
815 // --------- wxSocketClient Connect functions -------------------
816 // --------------------------------------------------------------
817 bool wxSocketClient::Connect(wxSockAddress& addr_man, bool WXUNUSED(wait) )
818 {
819 struct linger linger;
820
821 if (IsConnected())
822 Close();
823
824 // Initializes all socket stuff ...
825 // --------------------------------
826 m_fd = socket(addr_man.GetFamily(), SOCK_STREAM, 0);
827
828 if (m_fd < 0)
829 return FALSE;
830
831 m_connected = FALSE;
832
833 linger.l_onoff = 1;
834 linger.l_linger = 5;
835 setsockopt(m_fd, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(linger));
836
837 // Stay in touch with the state of things...
838
839 unsigned long flag = 1;
840 setsockopt(m_fd, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(int));
841
842 // Disable the nagle algorithm, which delays sends till the
843 // buffer is full (or a certain time period has passed?)...
844
845 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
846 flag = 1;
847 setsockopt(m_fd, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int));
848 #endif
849
850 struct sockaddr *remote;
851 size_t len;
852
853 addr_man.Build(remote, len);
854
855 if (connect(m_fd, remote, len) != 0)
856 return FALSE;
857
858 m_internal->SetFD(m_fd);
859
860 // Enables bg events.
861 // ------------------
862 Notify(TRUE);
863
864 m_connected = TRUE;
865 return TRUE;
866 }
867
868 bool wxSocketClient::WaitOnConnect(long seconds, long microseconds)
869 {
870 int ret = _Wait(seconds, microseconds, REQ_CONNECT | REQ_LOST);
871
872 if (ret)
873 m_connected = TRUE;
874
875 return m_connected;
876 }
877
878 void wxSocketClient::OnRequest(wxRequestEvent evt)
879 {
880 if (evt == EVT_CONNECT)
881 {
882 if (m_connected)
883 {
884 m_neededreq &= ~REQ_CONNECT;
885 return;
886 }
887 m_connected = TRUE;
888 return;
889 }
890 wxSocketBase::OnRequest(evt);
891 }
892
893 /////////////////////////////////////////////////////////////////
894 // wxSocketHandler ///////////////////////////////////////////////
895 /////////////////////////////////////////////////////////////////
896
897 wxSocketHandler *wxSocketHandler::master = NULL;
898 #if defined(__WINDOWS__)
899 static int win_initialized = 0;
900 #endif
901
902 // --------------------------------------------------------------
903 // --------- wxSocketHandler CONSTRUCTOR ------------------------
904 // --------------------------------------------------------------
905 wxSocketHandler::wxSocketHandler()
906 {
907 #if defined(__WINDOWS__)
908 if (!win_initialized)
909 {
910 WSADATA wsaData;
911
912 WSAStartup((1 << 8) | 1, &wsaData);
913 win_initialized = 1;
914 }
915 #endif
916
917 socks = new wxList;
918
919 #ifndef __WINDOWS__
920 signal(SIGPIPE, SIG_IGN);
921 #endif
922 }
923
924 // --------------------------------------------------------------
925 // --------- wxSocketHandler DESTRUCTOR -------------------------
926 // --------------------------------------------------------------
927 wxSocketHandler::~wxSocketHandler()
928 {
929 wxNode *next_node, *node = socks->First();
930
931 while (node)
932 {
933 wxSocketBase* sock = (wxSocketBase*)node->Data();
934
935 delete sock;
936 next_node = node->Next();
937 delete node;
938 node = next_node;
939 }
940
941 delete socks;
942
943 #ifdef __WINDOWS__
944 WSACleanup();
945 win_initialized = 0;
946 #endif
947 }
948
949 // --------------------------------------------------------------
950 // --------- wxSocketHandler registering functions --------------
951 // --------------------------------------------------------------
952
953 void wxSocketHandler::Register(wxSocketBase* sock)
954 {
955 wxNode *node;
956
957 for (node = socks->First(); node != NULL; node = node->Next())
958 {
959 wxSocketBase* s = (wxSocketBase*)node->Data();
960
961 if (s == sock)
962 return;
963 }
964
965 if (sock)
966 {
967 socks->Append(sock);
968 sock->SetHandler(this);
969 }
970 }
971
972 void wxSocketHandler::UnRegister(wxSocketBase* sock)
973 {
974 wxNode *node;
975
976 for (node = socks->First(); node; node = node->Next())
977 {
978 wxSocketBase* s = (wxSocketBase*)node->Data();
979
980 if (s == sock)
981 {
982 delete node;
983 sock->SetHandler(NULL);
984 return;
985 }
986 }
987 }
988
989 unsigned long wxSocketHandler::Count() const
990 {
991 return socks->Number();
992 }
993
994 // --------------------------------------------------------------
995 // --------- wxSocketHandler "big" wait functions ---------------
996 // --------------------------------------------------------------
997
998 int wxSocketHandler::Wait(long seconds, long microseconds)
999 {
1000 // TODO Needs the completely asynchronous notifier.
1001
1002 /*
1003 int i;
1004 int on_wait;
1005 wxNode *node;
1006 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1007 {
1008 wxSocketBase *sock = (wxSocketBase *)node->Data();
1009
1010 sock->SaveState();
1011
1012 sock->SetupCallbacks();
1013
1014 sock->Callback(handler_cbk);
1015 sock->CallbackData((char *)&on_wait);
1016 }
1017 on_wait = 0;
1018 if (seconds != -1)
1019 s_wake.Start((seconds*1000) + (microseconds/1000), TRUE);
1020
1021 while (!on_wait)
1022 PROCESS_EVENTS();
1023
1024 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1025 {
1026 wxSocketBase *sock = (wxSocketBase *)node->Data();
1027
1028 sock->RestoreState();
1029 }
1030
1031 if (on_wait == -2)
1032 return 0;
1033
1034 return on_wait;
1035 */
1036 return 0;
1037 }
1038
1039 void wxSocketHandler::YieldSock()
1040 {
1041 wxNode *node;
1042
1043 // Nothing to do anymore here except waiting for the queue emptying.
1044 for (node = socks->First(); node; node=node->Next()) {
1045 wxSocketBase *sock = (wxSocketBase *)node->Data();
1046
1047 sock->m_internal->WaitForEnd(NULL);
1048 }
1049 }
1050
1051 // --------------------------------------------------------------
1052 // --------- wxSocketHandler: create and register the socket ----
1053 // --------------------------------------------------------------
1054 wxSocketServer *wxSocketHandler::CreateServer(wxSockAddress& addr,
1055 wxSocketBase::wxSockFlags flags)
1056 {
1057 wxSocketServer *serv = new wxSocketServer(addr, flags);
1058
1059 Register(serv);
1060 return serv;
1061 }
1062
1063 wxSocketClient *wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags)
1064 {
1065 wxSocketClient *client = new wxSocketClient(flags);
1066
1067 Register(client);
1068 return client;
1069 }
1070
1071 bool wxSocketModule::OnInit()
1072 {
1073 wxSocketHandler::master = new wxSocketHandler();
1074 return TRUE;
1075 }
1076
1077 void wxSocketModule::OnExit()
1078 {
1079 delete wxSocketHandler::master;
1080 wxSocketHandler::master = NULL;
1081 }
1082
1083 #endif
1084 // __WXSTUBS__
1085
1086 #endif
1087 // wxUSE_SOCKETS