1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/sockmsw.cpp
3 // Purpose: MSW-specific socket code
4 // Authors: Guilhem Lavaux, Guillermo Rodriguez Garcia
6 // Copyright: (C) 1999-1997, Guilhem Lavaux
7 // (C) 1999-2000, Guillermo Rodriguez Garcia
8 // (C) 2008 Vadim Zeitlin
10 // License: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
14 // For compilers that support precompilation, includes "wx.h".
15 #include "wx/wxprec.h"
23 /* including rasasync.h (included from windows.h itself included from
24 * wx/setup.h and/or winsock.h results in this warning for
25 * RPCNOTIFICATION_ROUTINE
28 # pragma warning(disable:4115) /* named type definition in parentheses */
31 #include "wx/private/socket.h"
32 #include "wx/msw/private.h" // for wxGetInstance()
33 #include "wx/apptrait.h"
34 #include "wx/thread.h"
35 #include "wx/dynlib.h"
40 * As WSAAsyncSelect is not present on WinCE, it now uses WSACreateEvent,
41 * WSAEventSelect, WSAWaitForMultipleEvents and WSAEnumNetworkEvents. When
42 * enabling eventhandling for a socket a new thread it created that keeps track
43 * of the events and posts a messageto the hidden window to use the standard
46 #include "wx/msw/wince/net.h"
47 #include "wx/hashmap.h"
48 WX_DECLARE_HASH_MAP(int,bool,wxIntegerHash
,wxIntegerEqual
,SocketHash
);
51 #define isdigit(x) (x > 47 && x < 58)
53 #include "wx/msw/wince/net.h"
58 # pragma warning(default:4115) /* named type definition in parentheses */
61 #define CLASSNAME TEXT("_wxSocket_Internal_Window_Class")
63 /* implemented in utils.cpp */
64 extern "C" WXDLLIMPEXP_BASE HWND
65 wxCreateHiddenWindow(LPCTSTR
*pclassname
, LPCTSTR classname
, WNDPROC wndproc
);
67 /* Maximum number of different wxSocket objects at a given time.
68 * This value can be modified at will, but it CANNOT be greater
69 * than (0x7FFF - WM_USER + 1)
71 #define MAXSOCKETS 1024
73 #if (MAXSOCKETS > (0x7FFF - WM_USER + 1))
74 #error "MAXSOCKETS is too big!"
78 typedef int (PASCAL
*WSAAsyncSelect_t
)(SOCKET
,HWND
,u_int
,long);
80 /* Typedef the needed function prototypes and the WSANETWORKEVENTS structure
82 typedef struct _WSANETWORKEVENTS
{
85 } WSANETWORKEVENTS
, FAR
* LPWSANETWORKEVENTS
;
86 typedef HANDLE (PASCAL
*WSACreateEvent_t
)();
87 typedef int (PASCAL
*WSAEventSelect_t
)(SOCKET
,HANDLE
,long);
88 typedef int (PASCAL
*WSAWaitForMultipleEvents_t
)(long,HANDLE
,BOOL
,long,BOOL
);
89 typedef int (PASCAL
*WSAEnumNetworkEvents_t
)(SOCKET
,HANDLE
,LPWSANETWORKEVENTS
);
92 LRESULT CALLBACK
wxSocket_Internal_WinProc(HWND
, UINT
, WPARAM
, LPARAM
);
94 /* Global variables */
97 wxCRIT_SECT_DECLARE_MEMBER(gs_critical
);
98 static wxSocketImplMSW
*socketList
[MAXSOCKETS
];
99 static int firstAvailable
;
102 static WSAAsyncSelect_t gs_WSAAsyncSelect
= NULL
;
104 static SocketHash socketHash
;
105 static unsigned int currSocket
;
106 HANDLE hThread
[MAXSOCKETS
];
107 static WSACreateEvent_t gs_WSACreateEvent
= NULL
;
108 static WSAEventSelect_t gs_WSAEventSelect
= NULL
;
109 static WSAWaitForMultipleEvents_t gs_WSAWaitForMultipleEvents
= NULL
;
110 static WSAEnumNetworkEvents_t gs_WSAEnumNetworkEvents
= NULL
;
111 /* This structure will be used to pass data on to the thread that handles socket events.
113 typedef struct thread_data
{
115 unsigned long msgnumber
;
117 unsigned long lEvent
;
122 /* This thread handles socket events on WinCE using WSAEventSelect() as
123 * WSAAsyncSelect is not supported. When an event occurs for the socket, it is
124 * checked what kind of event happend and the correct message gets posted so
125 * that the hidden window can handle it as it would in other MSW builds.
127 DWORD WINAPI
SocketThread(LPVOID data
)
129 WSANETWORKEVENTS NetworkEvents
;
130 thread_data
* d
= (thread_data
*)data
;
132 HANDLE NetworkEvent
= gs_WSACreateEvent();
133 gs_WSAEventSelect(d
->fd
, NetworkEvent
, d
->lEvent
);
135 while(socketHash
[d
->fd
] == true)
137 if ((gs_WSAWaitForMultipleEvents(1, &NetworkEvent
, FALSE
,INFINITE
, FALSE
)) == WAIT_FAILED
)
139 printf("WSAWaitForMultipleEvents failed with error %d\n", WSAGetLastError());
142 if (gs_WSAEnumNetworkEvents(d
->fd
,NetworkEvent
, &NetworkEvents
) == SOCKET_ERROR
)
144 printf("WSAEnumNetworkEvents failed with error %d\n", WSAGetLastError());
148 long flags
= NetworkEvents
.lNetworkEvents
;
150 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_READ
);
151 if (flags
& FD_WRITE
)
152 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_WRITE
);
154 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_OOB
);
155 if (flags
& FD_ACCEPT
)
156 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_ACCEPT
);
157 if (flags
& FD_CONNECT
)
158 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_CONNECT
);
159 if (flags
& FD_CLOSE
)
160 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_CLOSE
);
163 gs_WSAEventSelect(d
->fd
, NetworkEvent
, 0);
169 // ----------------------------------------------------------------------------
170 // MSW implementation of wxSocketManager
171 // ----------------------------------------------------------------------------
173 class wxSocketMSWManager
: public wxSocketManager
176 virtual bool OnInit();
177 virtual void OnExit();
179 virtual wxSocketImpl
*CreateSocket(wxSocketBase
& wxsocket
)
181 return new wxSocketImplMSW(wxsocket
);
183 virtual void Install_Callback(wxSocketImpl
*socket
,
184 wxSocketNotify event
= wxSOCKET_LOST
);
185 virtual void Uninstall_Callback(wxSocketImpl
*socket
,
186 wxSocketNotify event
= wxSOCKET_LOST
);
189 static wxDynamicLibrary gs_wsock32dll
;
192 wxDynamicLibrary
wxSocketMSWManager::gs_wsock32dll
;
194 bool wxSocketMSWManager::OnInit()
196 static LPCTSTR pclassname
= NULL
;
199 /* Create internal window for event notifications */
200 hWin
= wxCreateHiddenWindow(&pclassname
, CLASSNAME
, wxSocket_Internal_WinProc
);
204 /* Initialize socket list */
205 for (i
= 0; i
< MAXSOCKETS
; i
++)
207 socketList
[i
] = NULL
;
211 // we don't link with wsock32.dll (or ws2 in CE case) statically to avoid
212 // dependencies on it for all the application using wx even if they don't use
215 #define WINSOCK_DLL_NAME wxT("ws2.dll")
217 #define WINSOCK_DLL_NAME wxT("wsock32.dll")
220 gs_wsock32dll
.Load(WINSOCK_DLL_NAME
, wxDL_VERBATIM
| wxDL_QUIET
);
221 if ( !gs_wsock32dll
.IsLoaded() )
225 wxDL_INIT_FUNC(gs_
, WSAAsyncSelect
, gs_wsock32dll
);
226 if ( !gs_WSAAsyncSelect
)
229 wxDL_INIT_FUNC(gs_
, WSAEventSelect
, gs_wsock32dll
);
230 if ( !gs_WSAEventSelect
)
233 wxDL_INIT_FUNC(gs_
, WSACreateEvent
, gs_wsock32dll
);
234 if ( !gs_WSACreateEvent
)
237 wxDL_INIT_FUNC(gs_
, WSAWaitForMultipleEvents
, gs_wsock32dll
);
238 if ( !gs_WSAWaitForMultipleEvents
)
241 wxDL_INIT_FUNC(gs_
, WSAEnumNetworkEvents
, gs_wsock32dll
);
242 if ( !gs_WSAEnumNetworkEvents
)
246 #endif // !__WXWINCE__/__WXWINCE__
248 // finally initialize WinSock
250 return WSAStartup((1 << 8) | 1, &wsaData
) == 0;
253 void wxSocketMSWManager::OnExit()
256 /* Delete the threads here */
257 for(unsigned int i
=0; i
< currSocket
; i
++)
258 CloseHandle(hThread
[i
]);
260 /* Destroy internal window */
262 UnregisterClass(CLASSNAME
, wxGetInstance());
266 gs_wsock32dll
.Unload();
269 /* Per-socket GUI initialization / cleanup */
271 wxSocketImplMSW::wxSocketImplMSW(wxSocketBase
& wxsocket
)
272 : wxSocketImpl(wxsocket
)
274 /* Allocate a new message number for this socket */
275 wxCRIT_SECT_LOCKER(lock
, gs_critical
);
277 int i
= firstAvailable
;
278 while (socketList
[i
] != NULL
)
280 i
= (i
+ 1) % MAXSOCKETS
;
282 if (i
== firstAvailable
) /* abort! */
284 m_msgnumber
= 0; // invalid
288 socketList
[i
] = this;
289 firstAvailable
= (i
+ 1) % MAXSOCKETS
;
290 m_msgnumber
= (i
+ WM_USER
);
293 wxSocketImplMSW::~wxSocketImplMSW()
295 /* Remove the socket from the list */
296 wxCRIT_SECT_LOCKER(lock
, gs_critical
);
300 // we need to remove any pending messages for this socket to avoid having
301 // them sent to a new socket which could reuse the same message number as
302 // soon as we destroy this one
304 while ( ::PeekMessage(&msg
, hWin
, m_msgnumber
, m_msgnumber
, PM_REMOVE
) )
307 socketList
[m_msgnumber
- WM_USER
] = NULL
;
309 //else: the socket has never been created successfully
312 /* Windows proc for asynchronous event handling */
314 LRESULT CALLBACK
wxSocket_Internal_WinProc(HWND hWnd
,
319 if ( uMsg
< WM_USER
|| uMsg
> (WM_USER
+ MAXSOCKETS
- 1))
320 return DefWindowProc(hWnd
, uMsg
, wParam
, lParam
);
322 wxSocketImplMSW
*socket
;
323 wxSocketNotify event
= (wxSocketNotify
)-1;
325 wxCRIT_SECT_LOCKER(lock
, gs_critical
);
327 socket
= socketList
[(uMsg
- WM_USER
)];
331 // the socket may be already closed but we could still receive
332 // notifications for it sent (asynchronously) before it got closed
333 if ( socket
->m_fd
== INVALID_SOCKET
)
336 wxASSERT_MSG( socket
->m_fd
== (SOCKET
)wParam
,
337 "mismatch between message and socket?" );
339 switch WSAGETSELECTEVENT(lParam
)
342 event
= wxSOCKET_INPUT
;
346 event
= wxSOCKET_OUTPUT
;
350 event
= wxSOCKET_CONNECTION
;
354 event
= WSAGETSELECTERROR(lParam
) ? wxSOCKET_LOST
355 : wxSOCKET_CONNECTION
;
359 event
= wxSOCKET_LOST
;
363 wxFAIL_MSG( "unexpected socket notification" );
366 } // unlock gs_critical
368 socket
->NotifyOnStateChange(event
);
374 * Enable all event notifications; we need to be notified of all
375 * events for internal processing, but we will only notify users
376 * when an appropriate callback function has been installed.
378 void wxSocketMSWManager::Install_Callback(wxSocketImpl
*socket_
,
379 wxSocketNotify
WXUNUSED(event
))
381 wxSocketImplMSW
* const socket
= static_cast<wxSocketImplMSW
*>(socket_
);
383 if (socket
->m_fd
!= INVALID_SOCKET
)
385 /* We could probably just subscribe to all events regardless
386 * of the socket type, but MS recommends to do it this way.
388 long lEvent
= socket
->m_server
?
389 FD_ACCEPT
: (FD_READ
| FD_WRITE
| FD_CONNECT
| FD_CLOSE
);
391 gs_WSAAsyncSelect(socket
->m_fd
, hWin
, socket
->m_msgnumber
, lEvent
);
394 * WinCE creates a thread for socket event handling.
395 * All needed parameters get passed through the thread_data structure.
398 thread_data
* d
= new thread_data
;
401 d
->msgnumber
= socket
->m_msgnumber
;
402 d
->fd
= socket
->m_fd
;
403 socketHash
[socket
->m_fd
] = true;
404 hThread
[currSocket
++] = CreateThread(NULL
, 0, &SocketThread
,(LPVOID
)d
, 0, NULL
);
410 * Disable event notifications (used when shutting down the socket)
412 void wxSocketMSWManager::Uninstall_Callback(wxSocketImpl
*socket_
,
413 wxSocketNotify
WXUNUSED(event
))
415 wxSocketImplMSW
* const socket
= static_cast<wxSocketImplMSW
*>(socket_
);
417 if (socket
->m_fd
!= INVALID_SOCKET
)
420 gs_WSAAsyncSelect(socket
->m_fd
, hWin
, socket
->m_msgnumber
, 0);
423 socketHash
[socket
->m_fd
] = false;
428 // set the wxBase variable to point to our wxSocketManager implementation
430 // see comments in wx/apptrait.h for the explanation of why do we do it
432 static struct ManagerSetter
436 static wxSocketMSWManager s_manager
;
437 wxAppTraits::SetDefaultSocketManager(&s_manager
);
441 // see the relative linker macro in socket.cpp
442 wxFORCE_LINK_THIS_MODULE( mswsocket
);
444 // ============================================================================
445 // wxSocketImpl implementation
446 // ============================================================================
448 void wxSocketImplMSW::DoClose()
450 wxSocketManager::Get()->Uninstall_Callback(this);
455 wxSocketError
wxSocketImplMSW::GetLastError() const
457 switch ( WSAGetLastError() )
460 return wxSOCKET_NOERROR
;
463 return wxSOCKET_INVSOCK
;
466 return wxSOCKET_WOULDBLOCK
;
469 return wxSOCKET_IOERR
;
473 #endif // wxUSE_SOCKETS