]> git.saurik.com Git - wxWidgets.git/blame_incremental - include/wx/socket.h
Implement monitoring of file descriptors in wxMotif event loop.
[wxWidgets.git] / include / wx / socket.h
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: wx/socket.h
3// Purpose: Socket handling classes
4// Authors: Guilhem Lavaux, Guillermo Rodriguez Garcia
5// Modified by:
6// Created: April 1997
7// RCS-ID: $Id$
8// Copyright: (c) Guilhem Lavaux
9// Licence: wxWindows licence
10/////////////////////////////////////////////////////////////////////////////
11
12#ifndef _WX_SOCKET_H_
13#define _WX_SOCKET_H_
14
15#include "wx/defs.h"
16
17#if wxUSE_SOCKETS
18
19// ---------------------------------------------------------------------------
20// wxSocket headers
21// ---------------------------------------------------------------------------
22
23#include "wx/event.h"
24#include "wx/sckaddr.h"
25#include "wx/list.h"
26
27class wxSocketImpl;
28
29// ------------------------------------------------------------------------
30// Types and constants
31// ------------------------------------------------------------------------
32
33// Define the type of native sockets.
34#if defined(__WINDOWS__)
35 // Although socket descriptors are still 32 bit values, even under Win64,
36 // the socket type is 64 bit there.
37 typedef wxUIntPtr wxSOCKET_T;
38#else
39 typedef int wxSOCKET_T;
40#endif
41
42
43// Types of different socket notifications or events.
44//
45// NB: the values here should be consecutive and start with 0 as they are
46// used to construct the wxSOCKET_XXX_FLAG bit mask values below
47enum wxSocketNotify
48{
49 wxSOCKET_INPUT,
50 wxSOCKET_OUTPUT,
51 wxSOCKET_CONNECTION,
52 wxSOCKET_LOST
53};
54
55enum
56{
57 wxSOCKET_INPUT_FLAG = 1 << wxSOCKET_INPUT,
58 wxSOCKET_OUTPUT_FLAG = 1 << wxSOCKET_OUTPUT,
59 wxSOCKET_CONNECTION_FLAG = 1 << wxSOCKET_CONNECTION,
60 wxSOCKET_LOST_FLAG = 1 << wxSOCKET_LOST
61};
62
63// this is a combination of the bit masks defined above
64typedef int wxSocketEventFlags;
65
66enum wxSocketError
67{
68 wxSOCKET_NOERROR = 0,
69 wxSOCKET_INVOP,
70 wxSOCKET_IOERR,
71 wxSOCKET_INVADDR,
72 wxSOCKET_INVSOCK,
73 wxSOCKET_NOHOST,
74 wxSOCKET_INVPORT,
75 wxSOCKET_WOULDBLOCK,
76 wxSOCKET_TIMEDOUT,
77 wxSOCKET_MEMERR,
78 wxSOCKET_OPTERR
79};
80
81// socket options/flags bit masks
82enum
83{
84 wxSOCKET_NONE = 0x0000,
85 wxSOCKET_NOWAIT_READ = 0x0001,
86 wxSOCKET_NOWAIT_WRITE = 0x0002,
87 wxSOCKET_NOWAIT = wxSOCKET_NOWAIT_READ | wxSOCKET_NOWAIT_WRITE,
88 wxSOCKET_WAITALL_READ = 0x0004,
89 wxSOCKET_WAITALL_WRITE = 0x0008,
90 wxSOCKET_WAITALL = wxSOCKET_WAITALL_READ | wxSOCKET_WAITALL_WRITE,
91 wxSOCKET_BLOCK = 0x0010,
92 wxSOCKET_REUSEADDR = 0x0020,
93 wxSOCKET_BROADCAST = 0x0040,
94 wxSOCKET_NOBIND = 0x0080
95};
96
97typedef int wxSocketFlags;
98
99// socket kind values (badly defined, don't use)
100enum wxSocketType
101{
102 wxSOCKET_UNINIT,
103 wxSOCKET_CLIENT,
104 wxSOCKET_SERVER,
105 wxSOCKET_BASE,
106 wxSOCKET_DATAGRAM
107};
108
109
110// event
111class WXDLLIMPEXP_FWD_NET wxSocketEvent;
112wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_NET, wxEVT_SOCKET, wxSocketEvent);
113
114// --------------------------------------------------------------------------
115// wxSocketBase
116// --------------------------------------------------------------------------
117
118class WXDLLIMPEXP_NET wxSocketBase : public wxObject
119{
120public:
121 // Public interface
122 // ----------------
123
124 // ctors and dtors
125 wxSocketBase();
126 wxSocketBase(wxSocketFlags flags, wxSocketType type);
127 virtual ~wxSocketBase();
128 void Init();
129 bool Destroy();
130
131 // state
132 bool Ok() const { return IsOk(); }
133 bool IsOk() const { return m_impl != NULL; }
134 bool Error() const { return LastError() != wxSOCKET_NOERROR; }
135 bool IsClosed() const { return m_closed; }
136 bool IsConnected() const { return m_connected; }
137 bool IsData() { return WaitForRead(0, 0); }
138 bool IsDisconnected() const { return !IsConnected(); }
139 wxUint32 LastCount() const { return m_lcount; }
140 wxUint32 LastReadCount() const { return m_lcount_read; }
141 wxUint32 LastWriteCount() const { return m_lcount_write; }
142 wxSocketError LastError() const;
143 void SaveState();
144 void RestoreState();
145
146 // addresses
147 virtual bool GetLocal(wxSockAddress& addr_man) const;
148 virtual bool GetPeer(wxSockAddress& addr_man) const;
149 virtual bool SetLocal(const wxIPV4address& local);
150
151 // base IO
152 virtual bool Close();
153 void ShutdownOutput();
154 wxSocketBase& Discard();
155 wxSocketBase& Peek(void* buffer, wxUint32 nbytes);
156 wxSocketBase& Read(void* buffer, wxUint32 nbytes);
157 wxSocketBase& ReadMsg(void *buffer, wxUint32 nbytes);
158 wxSocketBase& Unread(const void *buffer, wxUint32 nbytes);
159 wxSocketBase& Write(const void *buffer, wxUint32 nbytes);
160 wxSocketBase& WriteMsg(const void *buffer, wxUint32 nbytes);
161
162 // all Wait() functions wait until their condition is satisfied or the
163 // timeout expires; if seconds == -1 (default) then m_timeout value is used
164 //
165 // it is also possible to call InterruptWait() to cancel any current Wait()
166
167 // wait for anything at all to happen with this socket
168 bool Wait(long seconds = -1, long milliseconds = 0);
169
170 // wait until we can read from or write to the socket without blocking
171 // (notice that this does not mean that the operation will succeed but only
172 // that it will return immediately)
173 bool WaitForRead(long seconds = -1, long milliseconds = 0);
174 bool WaitForWrite(long seconds = -1, long milliseconds = 0);
175
176 // wait until the connection is terminated
177 bool WaitForLost(long seconds = -1, long milliseconds = 0);
178
179 void InterruptWait() { m_interrupt = true; }
180
181
182 wxSocketFlags GetFlags() const { return m_flags; }
183 void SetFlags(wxSocketFlags flags);
184 virtual void SetTimeout(long seconds);
185 long GetTimeout() const { return m_timeout; }
186
187 bool GetOption(int level, int optname, void *optval, int *optlen);
188 bool SetOption(int level, int optname, const void *optval, int optlen);
189 wxUint32 GetLastIOSize() const { return m_lcount; }
190 wxUint32 GetLastIOReadSize() const { return m_lcount_read; }
191 wxUint32 GetLastIOWriteSize() const { return m_lcount_write; }
192
193 // event handling
194 void *GetClientData() const { return m_clientData; }
195 void SetClientData(void *data) { m_clientData = data; }
196 void SetEventHandler(wxEvtHandler& handler, int id = wxID_ANY);
197 void SetNotify(wxSocketEventFlags flags);
198 void Notify(bool notify);
199
200 // Get the underlying socket descriptor.
201 wxSOCKET_T GetSocket() const;
202
203 // initialize/shutdown the sockets (done automatically so there is no need
204 // to call these functions usually)
205 //
206 // should always be called from the main thread only so one of the cases
207 // where they should indeed be called explicitly is when the first wxSocket
208 // object in the application is created in a different thread
209 static bool Initialize();
210 static void Shutdown();
211
212 // check if wxSocket had been already initialized
213 //
214 // notice that this function should be only called from the main thread as
215 // otherwise it is inherently unsafe because Initialize/Shutdown() may be
216 // called concurrently with it in the main thread
217 static bool IsInitialized();
218
219 // Implementation from now on
220 // --------------------------
221
222 // do not use, should be private (called from wxSocketImpl only)
223 void OnRequest(wxSocketNotify notify);
224
225 // do not use, not documented nor supported
226 bool IsNoWait() const { return ((m_flags & wxSOCKET_NOWAIT) != 0); }
227 wxSocketType GetType() const { return m_type; }
228
229private:
230 friend class wxSocketClient;
231 friend class wxSocketServer;
232 friend class wxDatagramSocket;
233
234 // low level IO
235 wxUint32 DoRead(void* buffer, wxUint32 nbytes);
236 wxUint32 DoWrite(const void *buffer, wxUint32 nbytes);
237
238 // wait until the given flags are set for this socket or the given timeout
239 // (or m_timeout) expires
240 //
241 // notice that wxSOCKET_LOST_FLAG is always taken into account and the
242 // function returns -1 if the connection was lost; otherwise it returns
243 // true if any of the events specified by flags argument happened or false
244 // if the timeout expired
245 int DoWait(long timeout, wxSocketEventFlags flags);
246
247 // a helper calling DoWait() using the same convention as the public
248 // WaitForXXX() functions use, i.e. use our timeout if seconds == -1 or the
249 // specified timeout otherwise
250 int DoWait(long seconds, long milliseconds, wxSocketEventFlags flags);
251
252 // another helper calling DoWait() using our m_timeout
253 int DoWaitWithTimeout(wxSocketEventFlags flags)
254 {
255 return DoWait(m_timeout*1000, flags);
256 }
257
258 // pushback buffer
259 void Pushback(const void *buffer, wxUint32 size);
260 wxUint32 GetPushback(void *buffer, wxUint32 size, bool peek);
261
262 // store the given error as the LastError()
263 void SetError(wxSocketError error);
264
265private:
266 // socket
267 wxSocketImpl *m_impl; // port-specific implementation
268 wxSocketType m_type; // wxSocket type
269
270 // state
271 wxSocketFlags m_flags; // wxSocket flags
272 bool m_connected; // connected?
273 bool m_establishing; // establishing connection?
274 bool m_reading; // busy reading?
275 bool m_writing; // busy writing?
276 bool m_closed; // was the other end closed?
277 wxUint32 m_lcount; // last IO transaction size
278 wxUint32 m_lcount_read; // last IO transaction size of Read() direction.
279 wxUint32 m_lcount_write; // last IO transaction size of Write() direction.
280 unsigned long m_timeout; // IO timeout value in seconds
281 // (TODO: remove, wxSocketImpl has it too)
282 wxList m_states; // stack of states (TODO: remove!)
283 bool m_interrupt; // interrupt ongoing wait operations?
284 bool m_beingDeleted; // marked for delayed deletion?
285 wxIPV4address m_localAddress; // bind to local address?
286
287 // pushback buffer
288 void *m_unread; // pushback buffer
289 wxUint32 m_unrd_size; // pushback buffer size
290 wxUint32 m_unrd_cur; // pushback pointer (index into buffer)
291
292 // events
293 int m_id; // socket id
294 wxEvtHandler *m_handler; // event handler
295 void *m_clientData; // client data for events
296 bool m_notify; // notify events to users?
297 wxSocketEventFlags m_eventmask; // which events to notify?
298 wxSocketEventFlags m_eventsgot; // collects events received in OnRequest()
299
300
301 friend class wxSocketReadGuard;
302 friend class wxSocketWriteGuard;
303
304 wxDECLARE_NO_COPY_CLASS(wxSocketBase);
305 DECLARE_CLASS(wxSocketBase)
306};
307
308
309// --------------------------------------------------------------------------
310// wxSocketServer
311// --------------------------------------------------------------------------
312
313class WXDLLIMPEXP_NET wxSocketServer : public wxSocketBase
314{
315public:
316 wxSocketServer(const wxSockAddress& addr,
317 wxSocketFlags flags = wxSOCKET_NONE);
318
319 wxSocketBase* Accept(bool wait = true);
320 bool AcceptWith(wxSocketBase& socket, bool wait = true);
321
322 bool WaitForAccept(long seconds = -1, long milliseconds = 0);
323
324 wxDECLARE_NO_COPY_CLASS(wxSocketServer);
325 DECLARE_CLASS(wxSocketServer)
326};
327
328
329// --------------------------------------------------------------------------
330// wxSocketClient
331// --------------------------------------------------------------------------
332
333class WXDLLIMPEXP_NET wxSocketClient : public wxSocketBase
334{
335public:
336 wxSocketClient(wxSocketFlags flags = wxSOCKET_NONE);
337
338 virtual bool Connect(const wxSockAddress& addr, bool wait = true);
339 bool Connect(const wxSockAddress& addr,
340 const wxSockAddress& local,
341 bool wait = true);
342
343 bool WaitOnConnect(long seconds = -1, long milliseconds = 0);
344
345 // Sets initial socket buffer sizes using the SO_SNDBUF and SO_RCVBUF
346 // options before calling connect (either one can be -1 to leave it
347 // unchanged)
348 void SetInitialSocketBuffers(int recv, int send)
349 {
350 m_initialRecvBufferSize = recv;
351 m_initialSendBufferSize = send;
352 }
353
354private:
355 virtual bool DoConnect(const wxSockAddress& addr,
356 const wxSockAddress* local,
357 bool wait = true);
358
359 // buffer sizes, -1 if unset and defaults should be used
360 int m_initialRecvBufferSize;
361 int m_initialSendBufferSize;
362
363 wxDECLARE_NO_COPY_CLASS(wxSocketClient);
364 DECLARE_CLASS(wxSocketClient)
365};
366
367
368// --------------------------------------------------------------------------
369// wxDatagramSocket
370// --------------------------------------------------------------------------
371
372// WARNING: still in alpha stage
373
374class WXDLLIMPEXP_NET wxDatagramSocket : public wxSocketBase
375{
376public:
377 wxDatagramSocket(const wxSockAddress& addr,
378 wxSocketFlags flags = wxSOCKET_NONE);
379
380 wxDatagramSocket& RecvFrom(wxSockAddress& addr,
381 void *buf,
382 wxUint32 nBytes);
383 wxDatagramSocket& SendTo(const wxSockAddress& addr,
384 const void* buf,
385 wxUint32 nBytes);
386
387 /* TODO:
388 bool Connect(wxSockAddress& addr);
389 */
390
391private:
392 wxDECLARE_NO_COPY_CLASS(wxDatagramSocket);
393 DECLARE_CLASS(wxDatagramSocket)
394};
395
396
397// --------------------------------------------------------------------------
398// wxSocketEvent
399// --------------------------------------------------------------------------
400
401class WXDLLIMPEXP_NET wxSocketEvent : public wxEvent
402{
403public:
404 wxSocketEvent(int id = 0)
405 : wxEvent(id, wxEVT_SOCKET)
406 {
407 }
408
409 wxSocketNotify GetSocketEvent() const { return m_event; }
410 wxSocketBase *GetSocket() const
411 { return (wxSocketBase *) GetEventObject(); }
412 void *GetClientData() const { return m_clientData; }
413
414 virtual wxEvent *Clone() const { return new wxSocketEvent(*this); }
415 virtual wxEventCategory GetEventCategory() const { return wxEVT_CATEGORY_SOCKET; }
416
417public:
418 wxSocketNotify m_event;
419 void *m_clientData;
420
421 DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxSocketEvent)
422};
423
424
425typedef void (wxEvtHandler::*wxSocketEventFunction)(wxSocketEvent&);
426
427#define wxSocketEventHandler(func) \
428 wxEVENT_HANDLER_CAST(wxSocketEventFunction, func)
429
430#define EVT_SOCKET(id, func) \
431 wx__DECLARE_EVT1(wxEVT_SOCKET, id, wxSocketEventHandler(func))
432
433#endif // wxUSE_SOCKETS
434
435#endif // _WX_SOCKET_H_
436