1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Socket handling classes
4 // Authors: Guilhem Lavaux, Guillermo Rodriguez Garcia
8 // Copyright: (c) Guilhem Lavaux
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
19 // ---------------------------------------------------------------------------
21 // ---------------------------------------------------------------------------
24 #include "wx/sckaddr.h"
29 // ------------------------------------------------------------------------
30 // Types and constants
31 // ------------------------------------------------------------------------
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
;
39 typedef int wxSOCKET_T
;
43 // Types of different socket notifications or events.
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
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
63 // this is a combination of the bit masks defined above
64 typedef int wxSocketEventFlags
;
81 // socket options/flags bit masks
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
97 typedef int wxSocketFlags
;
99 // socket kind values (badly defined, don't use)
111 class WXDLLIMPEXP_FWD_NET wxSocketEvent
;
112 wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_NET
, wxEVT_SOCKET
, wxSocketEvent
);
114 // --------------------------------------------------------------------------
116 // --------------------------------------------------------------------------
118 class WXDLLIMPEXP_NET wxSocketBase
: public wxObject
126 wxSocketBase(wxSocketFlags flags
, wxSocketType type
);
127 virtual ~wxSocketBase();
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;
147 virtual bool GetLocal(wxSockAddress
& addr_man
) const;
148 virtual bool GetPeer(wxSockAddress
& addr_man
) const;
149 virtual bool SetLocal(const wxIPV4address
& local
);
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
);
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
165 // it is also possible to call InterruptWait() to cancel any current Wait()
167 // wait for anything at all to happen with this socket
168 bool Wait(long seconds
= -1, long milliseconds
= 0);
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);
176 // wait until the connection is terminated
177 bool WaitForLost(long seconds
= -1, long milliseconds
= 0);
179 void InterruptWait() { m_interrupt
= true; }
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
; }
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
; }
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
);
200 // Get the underlying socket descriptor.
201 wxSOCKET_T
GetSocket() const;
203 // initialize/shutdown the sockets (done automatically so there is no need
204 // to call these functions usually)
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();
212 // check if wxSocket had been already initialized
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();
219 // Implementation from now on
220 // --------------------------
222 // do not use, should be private (called from wxSocketImpl only)
223 void OnRequest(wxSocketNotify notify
);
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
; }
230 friend class wxSocketClient
;
231 friend class wxSocketServer
;
232 friend class wxDatagramSocket
;
235 wxUint32
DoRead(void* buffer
, wxUint32 nbytes
);
236 wxUint32
DoWrite(const void *buffer
, wxUint32 nbytes
);
238 // wait until the given flags are set for this socket or the given timeout
239 // (or m_timeout) expires
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
);
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
);
252 // another helper calling DoWait() using our m_timeout
253 int DoWaitWithTimeout(wxSocketEventFlags flags
)
255 return DoWait(m_timeout
*1000, flags
);
259 void Pushback(const void *buffer
, wxUint32 size
);
260 wxUint32
GetPushback(void *buffer
, wxUint32 size
, bool peek
);
262 // store the given error as the LastError()
263 void SetError(wxSocketError error
);
267 wxSocketImpl
*m_impl
; // port-specific implementation
268 wxSocketType m_type
; // wxSocket type
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?
288 void *m_unread
; // pushback buffer
289 wxUint32 m_unrd_size
; // pushback buffer size
290 wxUint32 m_unrd_cur
; // pushback pointer (index into buffer)
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()
301 friend class wxSocketReadGuard
;
302 friend class wxSocketWriteGuard
;
304 wxDECLARE_NO_COPY_CLASS(wxSocketBase
);
305 DECLARE_CLASS(wxSocketBase
)
309 // --------------------------------------------------------------------------
311 // --------------------------------------------------------------------------
313 class WXDLLIMPEXP_NET wxSocketServer
: public wxSocketBase
316 wxSocketServer(const wxSockAddress
& addr
,
317 wxSocketFlags flags
= wxSOCKET_NONE
);
319 wxSocketBase
* Accept(bool wait
= true);
320 bool AcceptWith(wxSocketBase
& socket
, bool wait
= true);
322 bool WaitForAccept(long seconds
= -1, long milliseconds
= 0);
324 wxDECLARE_NO_COPY_CLASS(wxSocketServer
);
325 DECLARE_CLASS(wxSocketServer
)
329 // --------------------------------------------------------------------------
331 // --------------------------------------------------------------------------
333 class WXDLLIMPEXP_NET wxSocketClient
: public wxSocketBase
336 wxSocketClient(wxSocketFlags flags
= wxSOCKET_NONE
);
338 virtual bool Connect(const wxSockAddress
& addr
, bool wait
= true);
339 bool Connect(const wxSockAddress
& addr
,
340 const wxSockAddress
& local
,
343 bool WaitOnConnect(long seconds
= -1, long milliseconds
= 0);
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
348 void SetInitialSocketBuffers(int recv
, int send
)
350 m_initialRecvBufferSize
= recv
;
351 m_initialSendBufferSize
= send
;
355 virtual bool DoConnect(const wxSockAddress
& addr
,
356 const wxSockAddress
* local
,
359 // buffer sizes, -1 if unset and defaults should be used
360 int m_initialRecvBufferSize
;
361 int m_initialSendBufferSize
;
363 wxDECLARE_NO_COPY_CLASS(wxSocketClient
);
364 DECLARE_CLASS(wxSocketClient
)
368 // --------------------------------------------------------------------------
370 // --------------------------------------------------------------------------
372 // WARNING: still in alpha stage
374 class WXDLLIMPEXP_NET wxDatagramSocket
: public wxSocketBase
377 wxDatagramSocket(const wxSockAddress
& addr
,
378 wxSocketFlags flags
= wxSOCKET_NONE
);
380 wxDatagramSocket
& RecvFrom(wxSockAddress
& addr
,
383 wxDatagramSocket
& SendTo(const wxSockAddress
& addr
,
388 bool Connect(wxSockAddress& addr);
392 wxDECLARE_NO_COPY_CLASS(wxDatagramSocket
);
393 DECLARE_CLASS(wxDatagramSocket
)
397 // --------------------------------------------------------------------------
399 // --------------------------------------------------------------------------
401 class WXDLLIMPEXP_NET wxSocketEvent
: public wxEvent
404 wxSocketEvent(int id
= 0)
405 : wxEvent(id
, wxEVT_SOCKET
)
409 wxSocketNotify
GetSocketEvent() const { return m_event
; }
410 wxSocketBase
*GetSocket() const
411 { return (wxSocketBase
*) GetEventObject(); }
412 void *GetClientData() const { return m_clientData
; }
414 virtual wxEvent
*Clone() const { return new wxSocketEvent(*this); }
415 virtual wxEventCategory
GetEventCategory() const { return wxEVT_CATEGORY_SOCKET
; }
418 wxSocketNotify m_event
;
421 DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxSocketEvent
)
425 typedef void (wxEvtHandler::*wxSocketEventFunction
)(wxSocketEvent
&);
427 #define wxSocketEventHandler(func) \
428 wxEVENT_HANDLER_CAST(wxSocketEventFunction, func)
430 #define EVT_SOCKET(id, func) \
431 wx__DECLARE_EVT1(wxEVT_SOCKET, id, wxSocketEventHandler(func))
433 #endif // wxUSE_SOCKETS
435 #endif // _WX_SOCKET_H_