]> git.saurik.com Git - wxWidgets.git/blob - src/common/socket.cpp
More key event work. Added SetDetectableAutoRepeat.
[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_neededreq = flags;
547 if (m_neededreq == 0)
548 m_internal->StopWaiter();
549 else
550 Notify(m_notify_state);
551 }
552
553 void wxSocketBase::Notify(bool notify)
554 {
555 m_notify_state = notify;
556 if (m_fd == INVALID_SOCKET)
557 return;
558
559 if (notify)
560 m_internal->ResumeWaiter();
561 else
562 m_internal->StopWaiter();
563 }
564
565 void wxSocketBase::OnRequest(wxRequestEvent req_evt)
566 {
567 wxSocketEvent event(m_id);
568 wxRequestNotify notify = EventToNotify(req_evt);
569
570 if ((m_neededreq & notify) == notify) {
571 event.m_socket = this;
572 event.m_skevt = req_evt;
573 ProcessEvent(event);
574 // TODOTODO
575 // OldOnNotify(req_evt);
576
577 // We disable the event reporting.
578 m_neededreq &= ~notify;
579 }
580 }
581
582 wxSocketEvent::wxSocketEvent(int id)
583 : wxEvent(id)
584 {
585 wxEventType type = (wxEventType)wxEVT_SOCKET;
586
587 SetEventType(type);
588 }
589
590 void wxSocketEvent::CopyObject(wxObject& obj_d) const
591 {
592 wxSocketEvent *event = (wxSocketEvent *)&obj_d;
593
594 wxEvent::CopyObject(obj_d);
595
596 event->m_skevt = m_skevt;
597 event->m_socket = m_socket;
598 }
599
600 void wxSocketBase::OldOnNotify(wxRequestEvent evt)
601 {
602 }
603
604 // --------------------------------------------------------------
605 // --------- wxSocketBase functions [Callback, CallbackData] ----
606 // --------------------------------------------------------------
607
608 void wxSocketBase::SetEventHandler(wxEvtHandler& h_evt, int id)
609 {
610 SetNextHandler(&h_evt);
611 m_id = id;
612 }
613
614 // --------------------------------------------------------------
615 // --------- wxSocketBase pushback library ----------------------
616 // --------------------------------------------------------------
617
618 void wxSocketBase::CreatePushbackAfter(const char *buffer, size_t size)
619 {
620 char *curr_pos;
621
622 if (m_unread != NULL)
623 m_unread = (char *) realloc(m_unread, m_unrd_size+size);
624 else
625 m_unread = (char *) malloc(size);
626 curr_pos = m_unread + m_unrd_size;
627
628 memcpy(curr_pos, buffer, size);
629 m_unrd_size += size;
630 }
631
632 void wxSocketBase::CreatePushbackBefore(const char *buffer, size_t size)
633 {
634 char *curr_pos, *new_buf;
635
636 new_buf = (char *) malloc(m_unrd_size+size);
637 curr_pos = new_buf + size;
638
639 memcpy(new_buf, buffer, size);
640 if (m_unrd_size != 0) {
641 memcpy(curr_pos, m_unread, m_unrd_size);
642 free(m_unread);
643 }
644 m_unread = new_buf;
645 m_unrd_size += size;
646 }
647
648 size_t wxSocketBase::GetPushback(char *buffer, size_t size, bool peek)
649 {
650 if (!m_unrd_size)
651 return 0;
652
653 if (size > m_unrd_size)
654 size = m_unrd_size;
655 memcpy(buffer, m_unread, size);
656
657 if (!peek) {
658 m_unrd_size -= size;
659 if (m_unrd_size == 0) {
660 free(m_unread);
661 m_unread = NULL;
662 }
663 }
664
665 return size;
666 }
667
668 // --------------------------------------------------------------
669 // --------- wxSocketBase buffer core requester -----------------
670 // --------------------------------------------------------------
671
672 void wxSocketBase::WantBuffer(char *buffer, size_t nbytes,
673 wxRequestEvent evt)
674 {
675 bool buf_timed_out;
676
677 if (m_fd == INVALID_SOCKET || !m_handler || !m_connected)
678 return;
679
680 SockRequest *buf = new SockRequest;
681
682 SaveState();
683 m_internal->StopWaiter();
684 buf->buffer = buffer;
685 buf->size = nbytes;
686 buf->done = FALSE;
687 buf->type = EventToNotify(evt);
688 buf->io_nbytes = 0;
689 buf->error = 0;
690 buf->wait = TRUE;
691 buf->timeout = 1000;
692 buf_timed_out = FALSE;
693
694 if (m_flags & SPEED)
695 m_internal->QueueRequest(buf, FALSE);
696 else
697 if (m_flags & NOWAIT)
698 m_internal->QueueRequest(buf, TRUE);
699 else
700 m_internal->QueueRequest(buf, TRUE);
701 m_lcount += buf->io_nbytes;
702 if (buf_timed_out)
703 m_error = ETIMEDOUT;
704 else
705 m_error = buf->error;
706
707 delete buf;
708 RestoreState();
709 }
710
711 // --------------------------------------------------------------
712 // wxSocketServer
713 // --------------------------------------------------------------
714
715 wxSocketServer::wxSocketServer(wxSockAddress& addr_man,
716 wxSockFlags flags) :
717 wxSocketBase(flags, SOCK_SERVER)
718 {
719 m_fd = socket(addr_man.GetFamily(), SOCK_STREAM, 0);
720
721 if (m_fd == INVALID_SOCKET)
722 return;
723
724 int flag = 1;
725 setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&flag, sizeof(int));
726
727 struct sockaddr *myaddr;
728 size_t len;
729
730 addr_man.Build(myaddr, len);
731 if (bind(m_fd, myaddr, addr_man.SockAddrLen()) < 0)
732 return;
733
734 if (listen(m_fd, 5) < 0) {
735 m_fd = INVALID_SOCKET;
736 return;
737 }
738
739 m_internal->SetFD(m_fd);
740
741 Notify(TRUE);
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->SetFD(fd2);
773
774 sock.m_internal->ResumeWaiter();
775
776 return TRUE;
777 }
778
779 wxSocketBase *wxSocketServer::Accept()
780 {
781 wxSocketBase* sock = new wxSocketBase();
782
783 sock->SetFlags((wxSockFlags)m_flags);
784
785 if (!AcceptWith(*sock))
786 return NULL;
787
788 if (m_handler)
789 m_handler->Register(sock);
790
791 return sock;
792 }
793
794 // --------------------------------------------------------------
795 // wxSocketClient
796 // --------------------------------------------------------------
797
798 // --------- wxSocketClient CONSTRUCTOR -------------------------
799 // --------------------------------------------------------------
800 wxSocketClient::wxSocketClient(wxSockFlags _flags) :
801 wxSocketBase(_flags, SOCK_CLIENT)
802 {
803 }
804
805 // --------------------------------------------------------------
806 // --------- wxSocketClient DESTRUCTOR --------------------------
807 // --------------------------------------------------------------
808 wxSocketClient::~wxSocketClient()
809 {
810 }
811
812 // --------------------------------------------------------------
813 // --------- wxSocketClient Connect functions -------------------
814 // --------------------------------------------------------------
815 bool wxSocketClient::Connect(wxSockAddress& addr_man, bool WXUNUSED(wait) )
816 {
817 struct linger linger;
818
819 if (IsConnected())
820 Close();
821
822 // Initializes all socket stuff ...
823 // --------------------------------
824 m_fd = socket(addr_man.GetFamily(), SOCK_STREAM, 0);
825
826 if (m_fd < 0)
827 return FALSE;
828
829 m_connected = FALSE;
830
831 linger.l_onoff = 1;
832 linger.l_linger = 5;
833 setsockopt(m_fd, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(linger));
834
835 // Stay in touch with the state of things...
836
837 unsigned long flag = 1;
838 setsockopt(m_fd, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(int));
839
840 // Disable the nagle algorithm, which delays sends till the
841 // buffer is full (or a certain time period has passed?)...
842
843 #if defined(__WINDOWS__) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
844 flag = 1;
845 setsockopt(m_fd, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int));
846 #endif
847
848 struct sockaddr *remote;
849 size_t len;
850
851 addr_man.Build(remote, len);
852
853 if (connect(m_fd, remote, len) != 0)
854 return FALSE;
855
856 m_internal->SetFD(m_fd);
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 m_neededreq &= ~REQ_CONNECT;
883 return;
884 }
885 m_connected = TRUE;
886 return;
887 }
888 wxSocketBase::OnRequest(evt);
889 }
890
891 /////////////////////////////////////////////////////////////////
892 // wxSocketHandler ///////////////////////////////////////////////
893 /////////////////////////////////////////////////////////////////
894
895 wxSocketHandler *wxSocketHandler::master = NULL;
896 #if defined(__WINDOWS__)
897 static int win_initialized = 0;
898 #endif
899
900 // --------------------------------------------------------------
901 // --------- wxSocketHandler CONSTRUCTOR ------------------------
902 // --------------------------------------------------------------
903 wxSocketHandler::wxSocketHandler()
904 {
905 #if defined(__WINDOWS__)
906 if (!win_initialized)
907 {
908 WSADATA wsaData;
909
910 WSAStartup((1 << 8) | 1, &wsaData);
911 win_initialized = 1;
912 }
913 #endif
914
915 socks = new wxList;
916
917 #ifndef __WINDOWS__
918 signal(SIGPIPE, SIG_IGN);
919 #endif
920 }
921
922 // --------------------------------------------------------------
923 // --------- wxSocketHandler DESTRUCTOR -------------------------
924 // --------------------------------------------------------------
925 wxSocketHandler::~wxSocketHandler()
926 {
927 wxNode *next_node, *node = socks->First();
928
929 while (node)
930 {
931 wxSocketBase* sock = (wxSocketBase*)node->Data();
932
933 delete sock;
934 next_node = node->Next();
935 delete node;
936 node = next_node;
937 }
938
939 delete socks;
940
941 #ifdef __WINDOWS__
942 WSACleanup();
943 win_initialized = 0;
944 #endif
945 }
946
947 // --------------------------------------------------------------
948 // --------- wxSocketHandler registering functions --------------
949 // --------------------------------------------------------------
950
951 void wxSocketHandler::Register(wxSocketBase* sock)
952 {
953 wxNode *node;
954
955 for (node = socks->First(); node != NULL; node = node->Next())
956 {
957 wxSocketBase* s = (wxSocketBase*)node->Data();
958
959 if (s == sock)
960 return;
961 }
962
963 if (sock)
964 {
965 socks->Append(sock);
966 sock->SetHandler(this);
967 }
968 }
969
970 void wxSocketHandler::UnRegister(wxSocketBase* sock)
971 {
972 wxNode *node;
973
974 for (node = socks->First(); node; node = node->Next())
975 {
976 wxSocketBase* s = (wxSocketBase*)node->Data();
977
978 if (s == sock)
979 {
980 delete node;
981 sock->SetHandler(NULL);
982 return;
983 }
984 }
985 }
986
987 unsigned long wxSocketHandler::Count() const
988 {
989 return socks->Number();
990 }
991
992 // --------------------------------------------------------------
993 // --------- wxSocketHandler "big" wait functions ---------------
994 // --------------------------------------------------------------
995
996 int wxSocketHandler::Wait(long seconds, long microseconds)
997 {
998 // TODO Needs the completely asynchronous notifier.
999
1000 /*
1001 int i;
1002 int on_wait;
1003 wxNode *node;
1004 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1005 {
1006 wxSocketBase *sock = (wxSocketBase *)node->Data();
1007
1008 sock->SaveState();
1009
1010 sock->SetupCallbacks();
1011
1012 sock->Callback(handler_cbk);
1013 sock->CallbackData((char *)&on_wait);
1014 }
1015 on_wait = 0;
1016 if (seconds != -1)
1017 s_wake.Start((seconds*1000) + (microseconds/1000), TRUE);
1018
1019 while (!on_wait)
1020 PROCESS_EVENTS();
1021
1022 for (node = socks->First(), i=0; node; node = node->Next(), i++)
1023 {
1024 wxSocketBase *sock = (wxSocketBase *)node->Data();
1025
1026 sock->RestoreState();
1027 }
1028
1029 if (on_wait == -2)
1030 return 0;
1031
1032 return on_wait;
1033 */
1034 return 0;
1035 }
1036
1037 void wxSocketHandler::YieldSock()
1038 {
1039 wxNode *node;
1040
1041 // Nothing to do anymore here except waiting for the queue emptying.
1042 for (node = socks->First(); node; node=node->Next()) {
1043 wxSocketBase *sock = (wxSocketBase *)node->Data();
1044
1045 sock->m_internal->WaitForEnd(NULL);
1046 }
1047 }
1048
1049 // --------------------------------------------------------------
1050 // --------- wxSocketHandler: create and register the socket ----
1051 // --------------------------------------------------------------
1052 wxSocketServer *wxSocketHandler::CreateServer(wxSockAddress& addr,
1053 wxSocketBase::wxSockFlags flags)
1054 {
1055 wxSocketServer *serv = new wxSocketServer(addr, flags);
1056
1057 Register(serv);
1058 return serv;
1059 }
1060
1061 wxSocketClient *wxSocketHandler::CreateClient(wxSocketBase::wxSockFlags flags)
1062 {
1063 wxSocketClient *client = new wxSocketClient(flags);
1064
1065 Register(client);
1066 return client;
1067 }
1068
1069 bool wxSocketModule::OnInit()
1070 {
1071 wxSocketHandler::master = new wxSocketHandler();
1072 return TRUE;
1073 }
1074
1075 void wxSocketModule::OnExit()
1076 {
1077 delete wxSocketHandler::master;
1078 wxSocketHandler::master = NULL;
1079 }
1080
1081 #endif
1082 // __WXSTUBS__
1083
1084 #endif
1085 // wxUSE_SOCKETS