1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket)
3 * Name: src/msw/gsockmsw.cpp
4 * Copyright: (c) Guilhem Lavaux
5 * Licence: wxWindows Licence
6 * Author: Guillermo Rodriguez Garcia <guille@iies.es>
7 * Purpose: GSocket GUI-specific MSW code
9 * -------------------------------------------------------------------------
12 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
22 * DONE: for WinCE we need to replace WSAAsyncSelect
23 * (Windows message-based notification of network events for a socket)
24 * with another mechanism.
25 * As WSAAsyncSelect is not present on WinCE, it now uses
26 * WSACreateEvent, WSAEventSelect, WSAWaitForMultipleEvents and WSAEnumNetworkEvents.
27 * When enabling eventhandling for a socket a new thread it created that keeps track of the events
28 * and posts a messageto the hidden window to use the standard message loop.
31 /* including rasasync.h (included from windows.h itself included from
32 * wx/setup.h and/or winsock.h results in this warning for
33 * RPCNOTIFICATION_ROUTINE
36 # pragma warning(disable:4115) /* named type definition in parentheses */
39 #include "wx/gsocket.h"
40 #include "wx/apptrait.h"
43 wxFORCE_LINK_THIS_MODULE(gsockmsw
)
45 extern "C" WXDLLIMPEXP_BASE HINSTANCE
wxGetInstance();
46 #define INSTANCE wxGetInstance()
50 #include "wx/msw/wince/net.h"
51 #include "wx/hashmap.h"
52 WX_DECLARE_HASH_MAP(int,bool,wxIntegerHash
,wxIntegerEqual
,SocketHash
);
64 # pragma warning(default:4115) /* named type definition in parentheses */
67 #define CLASSNAME TEXT("_GSocket_Internal_Window_Class")
69 /* implemented in utils.cpp */
70 extern "C" WXDLLIMPEXP_BASE HWND
71 wxCreateHiddenWindow(LPCTSTR
*pclassname
, LPCTSTR classname
, WNDPROC wndproc
);
73 /* Maximum number of different GSocket objects at a given time.
74 * This value can be modified at will, but it CANNOT be greater
75 * than (0x7FFF - WM_USER + 1)
77 #define MAXSOCKETS 1024
79 #if (MAXSOCKETS > (0x7FFF - WM_USER + 1))
80 #error "MAXSOCKETS is too big!"
84 typedef int (PASCAL
*WSAAsyncSelectFunc
)(SOCKET
,HWND
,u_int
,long);
86 /* Typedef the needed function prototypes and the WSANETWORKEVENTS structure
88 typedef struct _WSANETWORKEVENTS
{
91 } WSANETWORKEVENTS
, FAR
* LPWSANETWORKEVENTS
;
92 typedef HANDLE (PASCAL
*WSACreateEventFunc
)();
93 typedef int (PASCAL
*WSAEventSelectFunc
)(SOCKET
,HANDLE
,long);
94 typedef int (PASCAL
*WSAWaitForMultipleEventsFunc
)(long,HANDLE
,BOOL
,long,BOOL
);
95 typedef int (PASCAL
*WSAEnumNetworkEventsFunc
)(SOCKET
,HANDLE
,LPWSANETWORKEVENTS
);
98 LRESULT CALLBACK
_GSocket_Internal_WinProc(HWND
, UINT
, WPARAM
, LPARAM
);
100 /* Global variables */
103 static CRITICAL_SECTION critical
;
104 static GSocket
* socketList
[MAXSOCKETS
];
105 static int firstAvailable
;
108 static WSAAsyncSelectFunc gs_WSAAsyncSelect
= NULL
;
110 static SocketHash socketHash
;
111 static unsigned int currSocket
;
112 HANDLE hThread
[MAXSOCKETS
];
113 static WSACreateEventFunc gs_WSACreateEvent
= NULL
;
114 static WSAEventSelectFunc gs_WSAEventSelect
= NULL
;
115 static WSAWaitForMultipleEventsFunc gs_WSAWaitForMultipleEvents
= NULL
;
116 static WSAEnumNetworkEventsFunc gs_WSAEnumNetworkEvents
= NULL
;
117 /* This structure will be used to pass data on to the thread that handles socket events.
119 typedef struct thread_data
{
121 unsigned long msgnumber
;
123 unsigned long lEvent
;
127 static HMODULE gs_wsock32dll
= 0;
131 /* This thread handles socket events on WinCE using WSAEventSelect() as WSAAsyncSelect is not supported.
132 * When an event occures for the socket, it is checked what kind of event happend and the correct message gets posted
133 * so that the hidden window can handle it as it would in other MSW builds.
135 DWORD WINAPI
SocketThread(LPVOID data
)
137 WSANETWORKEVENTS NetworkEvents
;
138 thread_data
* d
= (thread_data
*)data
;
140 HANDLE NetworkEvent
= gs_WSACreateEvent();
141 gs_WSAEventSelect(d
->fd
, NetworkEvent
, d
->lEvent
);
143 while(socketHash
[d
->fd
] == true)
145 if ((gs_WSAWaitForMultipleEvents(1, &NetworkEvent
, FALSE
,INFINITE
, FALSE
)) == WAIT_FAILED
)
147 printf("WSAWaitForMultipleEvents failed with error %d\n", WSAGetLastError());
150 if (gs_WSAEnumNetworkEvents(d
->fd
,NetworkEvent
, &NetworkEvents
) == SOCKET_ERROR
)
152 printf("WSAEnumNetworkEvents failed with error %d\n", WSAGetLastError());
156 long flags
= NetworkEvents
.lNetworkEvents
;
158 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_READ
);
159 if (flags
& FD_WRITE
)
160 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_WRITE
);
162 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_OOB
);
163 if (flags
& FD_ACCEPT
)
164 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_ACCEPT
);
165 if (flags
& FD_CONNECT
)
166 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_CONNECT
);
167 if (flags
& FD_CLOSE
)
168 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_CLOSE
);
171 gs_WSAEventSelect(d
->fd
, NetworkEvent
, 0);
177 // ----------------------------------------------------------------------------
178 // MSW implementation of GSocketManager
179 // ----------------------------------------------------------------------------
181 class GSocketMSWManager
: public GSocketManager
184 virtual bool OnInit();
185 virtual void OnExit();
187 virtual bool Init_Socket(GSocket
*socket
);
188 virtual void Destroy_Socket(GSocket
*socket
);
190 virtual void Install_Callback(GSocket
*socket
, GSocketEvent event
);
191 virtual void Uninstall_Callback(GSocket
*socket
, GSocketEvent event
);
193 virtual void Enable_Events(GSocket
*socket
);
194 virtual void Disable_Events(GSocket
*socket
);
197 /* Global initializers */
199 bool GSocketMSWManager::OnInit()
201 static LPCTSTR pclassname
= NULL
;
204 /* Create internal window for event notifications */
205 hWin
= wxCreateHiddenWindow(&pclassname
, CLASSNAME
, _GSocket_Internal_WinProc
);
209 /* Initialize socket list */
210 InitializeCriticalSection(&critical
);
212 for (i
= 0; i
< MAXSOCKETS
; i
++)
214 socketList
[i
] = NULL
;
218 /* Load WSAAsyncSelect from wsock32.dll (we don't link against it
219 statically to avoid dependency on wsock32.dll for apps that don't use
222 gs_wsock32dll
= LoadLibrary(wxT("wsock32.dll"));
225 gs_WSAAsyncSelect
=(WSAAsyncSelectFunc
)GetProcAddress(gs_wsock32dll
,
227 if (!gs_WSAAsyncSelect
)
230 /* On WinCE we load ws2.dll which will provide the needed functions.
232 gs_wsock32dll
= LoadLibrary(wxT("ws2.dll"));
235 gs_WSAEventSelect
=(WSAEventSelectFunc
)GetProcAddress(gs_wsock32dll
,
236 wxT("WSAEventSelect"));
237 if (!gs_WSAEventSelect
)
240 gs_WSACreateEvent
=(WSACreateEventFunc
)GetProcAddress(gs_wsock32dll
,
241 wxT("WSACreateEvent"));
242 if (!gs_WSACreateEvent
)
245 gs_WSAWaitForMultipleEvents
=(WSAWaitForMultipleEventsFunc
)GetProcAddress(gs_wsock32dll
,
246 wxT("WSAWaitForMultipleEvents"));
247 if (!gs_WSAWaitForMultipleEvents
)
250 gs_WSAEnumNetworkEvents
=(WSAEnumNetworkEventsFunc
)GetProcAddress(gs_wsock32dll
,
251 wxT("WSAEnumNetworkEvents"));
252 if (!gs_WSAEnumNetworkEvents
)
261 void GSocketMSWManager::OnExit()
264 /* Delete the threads here */
265 for(unsigned int i
=0; i
< currSocket
; i
++)
266 CloseHandle(hThread
[i
]);
268 /* Destroy internal window */
270 UnregisterClass(CLASSNAME
, INSTANCE
);
272 /* Unlock wsock32.dll */
275 FreeLibrary(gs_wsock32dll
);
279 /* Delete critical section */
280 DeleteCriticalSection(&critical
);
283 /* Per-socket GUI initialization / cleanup */
285 bool GSocketMSWManager::Init_Socket(GSocket
*socket
)
289 /* Allocate a new message number for this socket */
290 EnterCriticalSection(&critical
);
293 while (socketList
[i
] != NULL
)
295 i
= (i
+ 1) % MAXSOCKETS
;
297 if (i
== firstAvailable
) /* abort! */
299 LeaveCriticalSection(&critical
);
303 socketList
[i
] = socket
;
304 firstAvailable
= (i
+ 1) % MAXSOCKETS
;
305 socket
->m_msgnumber
= (i
+ WM_USER
);
307 LeaveCriticalSection(&critical
);
312 void GSocketMSWManager::Destroy_Socket(GSocket
*socket
)
314 /* Remove the socket from the list */
315 EnterCriticalSection(&critical
);
316 if ( socket
->IsOk() )
318 const int msgnum
= socket
->m_msgnumber
;
320 // we need to remove any pending messages for this socket to avoid having
321 // them sent to a new socket which could reuse the same message number as
322 // soon as we destroy this one
324 while ( ::PeekMessage(&msg
, hWin
, msgnum
, msgnum
, PM_REMOVE
) )
327 socketList
[msgnum
- WM_USER
] = NULL
;
330 LeaveCriticalSection(&critical
);
333 void GSocketMSWManager::Install_Callback(GSocket
* WXUNUSED(socket
),
334 GSocketEvent
WXUNUSED(event
))
336 wxFAIL_MSG( _T("not used under MSW") );
339 void GSocketMSWManager::Uninstall_Callback(GSocket
* WXUNUSED(socket
),
340 GSocketEvent
WXUNUSED(event
))
342 wxFAIL_MSG( _T("not used under MSW") );
345 /* Windows proc for asynchronous event handling */
347 LRESULT CALLBACK
_GSocket_Internal_WinProc(HWND hWnd
,
354 GSocketCallback cback
;
357 if (uMsg
>= WM_USER
&& uMsg
<= (WM_USER
+ MAXSOCKETS
- 1))
359 EnterCriticalSection(&critical
);
360 socket
= socketList
[(uMsg
- WM_USER
)];
361 event
= (GSocketEvent
) -1;
365 /* Check that the socket still exists (it has not been
366 * destroyed) and for safety, check that the m_fd field
367 * is what we expect it to be.
369 if ((socket
!= NULL
) && (socket
->m_fd
== wParam
))
371 switch WSAGETSELECTEVENT(lParam
)
373 case FD_READ
: event
= GSOCK_INPUT
; break;
374 case FD_WRITE
: event
= GSOCK_OUTPUT
; break;
375 case FD_ACCEPT
: event
= GSOCK_CONNECTION
; break;
378 if (WSAGETSELECTERROR(lParam
) != 0)
381 event
= GSOCK_CONNECTION
;
384 case FD_CLOSE
: event
= GSOCK_LOST
; break;
389 cback
= socket
->m_cbacks
[event
];
390 data
= socket
->m_data
[event
];
392 if (event
== GSOCK_LOST
)
393 socket
->m_detected
= GSOCK_LOST_FLAG
;
395 socket
->m_detected
|= (1 << event
);
399 /* OK, we can now leave the critical section because we have
400 * already obtained the callback address (we make no further
401 * accesses to socket->whatever). However, the app should
402 * be prepared to handle events from a socket that has just
405 LeaveCriticalSection(&critical
);
408 (cback
)(socket
, event
, data
);
413 return DefWindowProc(hWnd
, uMsg
, wParam
, lParam
);
416 /* _GSocket_Enable_Events:
417 * Enable all event notifications; we need to be notified of all
418 * events for internal processing, but we will only notify users
419 * when an appropiate callback function has been installed.
421 void GSocketMSWManager::Enable_Events(GSocket
*socket
)
423 if (socket
->m_fd
!= INVALID_SOCKET
)
425 /* We could probably just subscribe to all events regardless
426 * of the socket type, but MS recommends to do it this way.
428 long lEvent
= socket
->m_server
?
429 FD_ACCEPT
: (FD_READ
| FD_WRITE
| FD_CONNECT
| FD_CLOSE
);
431 gs_WSAAsyncSelect(socket
->m_fd
, hWin
, socket
->m_msgnumber
, lEvent
);
434 * WinCE creates a thread for socket event handling.
435 * All needed parameters get passed through the thread_data structure.
438 thread_data
* d
= new thread_data
;
441 d
->msgnumber
= socket
->m_msgnumber
;
442 d
->fd
= socket
->m_fd
;
443 socketHash
[socket
->m_fd
] = true;
444 hThread
[currSocket
++] = CreateThread(NULL
, 0, &SocketThread
,(LPVOID
)d
, 0, NULL
);
449 /* _GSocket_Disable_Events:
450 * Disable event notifications (when shutdowning the socket)
452 void GSocketMSWManager::Disable_Events(GSocket
*socket
)
454 if (socket
->m_fd
!= INVALID_SOCKET
)
457 gs_WSAAsyncSelect(socket
->m_fd
, hWin
, socket
->m_msgnumber
, 0);
460 socketHash
[socket
->m_fd
] = false;
465 // set the wxBase variable to point to our GSocketManager implementation
467 // see comments in wx/msw/apptbase.h for the explanation of why do we do it
469 static struct ManagerSetter
473 static GSocketMSWManager s_manager
;
474 wxAppTraits::SetDefaultSocketManager(&s_manager
);
478 #endif // wxUSE_SOCKETS