added UDP test (see #10717)
[wxWidgets.git] / samples / sockets / server.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: server.cpp
3 // Purpose: Server for wxSocket demo
4 // Author: Guillermo Rodriguez Garcia <guille@iies.es>
5 // Modified by:
6 // Created: 1999/09/19
7 // RCS-ID: $Id$
8 // Copyright: (c) 1999 Guillermo Rodriguez Garcia
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ==========================================================================
13 // declarations
14 // ==========================================================================
15
16 // --------------------------------------------------------------------------
17 // headers
18 // --------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx/wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 # pragma hdrstop
25 #endif
26
27 // for all others, include the necessary headers
28 #ifndef WX_PRECOMP
29 # include "wx/wx.h"
30 #endif
31
32 #include "wx/socket.h"
33
34 // this example is currently written to use only IP or only IPv6 sockets, it
35 // should be extended to allow using either in the future
36 #if wxUSE_IPV6
37 typedef wxIPV6address IPaddress;
38 #else
39 typedef wxIPV4address IPaddress;
40 #endif
41
42 // --------------------------------------------------------------------------
43 // resources
44 // --------------------------------------------------------------------------
45
46 // the application icon
47 #include "mondrian.xpm"
48
49 // --------------------------------------------------------------------------
50 // classes
51 // --------------------------------------------------------------------------
52
53 // Define a new application type
54 class MyApp : public wxApp
55 {
56 public:
57 virtual bool OnInit();
58 };
59
60 // Define a new frame type: this is going to be our main frame
61 class MyFrame : public wxFrame
62 {
63 public:
64 MyFrame();
65 ~MyFrame();
66
67 // event handlers (these functions should _not_ be virtual)
68 void OnUDPTest(wxCommandEvent& event);
69 void OnQuit(wxCommandEvent& event);
70 void OnAbout(wxCommandEvent& event);
71 void OnServerEvent(wxSocketEvent& event);
72 void OnSocketEvent(wxSocketEvent& event);
73
74 void Test1(wxSocketBase *sock);
75 void Test2(wxSocketBase *sock);
76 void Test3(wxSocketBase *sock);
77
78 // convenience functions
79 void UpdateStatusBar();
80
81 private:
82 wxSocketServer *m_server;
83 wxTextCtrl *m_text;
84 wxMenu *m_menuFile;
85 wxMenuBar *m_menuBar;
86 bool m_busy;
87 int m_numClients;
88
89 // any class wishing to process wxWidgets events must use this macro
90 DECLARE_EVENT_TABLE()
91 };
92
93 // simple helper class to log start and end of each test
94 class TestLogger
95 {
96 public:
97 TestLogger(const wxString& name) : m_name(name)
98 {
99 wxLogMessage("=== %s begins ===", m_name);
100 }
101
102 ~TestLogger()
103 {
104 wxLogMessage("=== %s ends ===", m_name);
105 }
106
107 private:
108 const wxString m_name;
109 };
110
111 // --------------------------------------------------------------------------
112 // constants
113 // --------------------------------------------------------------------------
114
115 // IDs for the controls and the menu commands
116 enum
117 {
118 // menu items
119 SERVER_UDPTEST = 10,
120 SERVER_QUIT = wxID_EXIT,
121 SERVER_ABOUT = wxID_ABOUT,
122
123 // id for sockets
124 SERVER_ID = 100,
125 SOCKET_ID
126 };
127
128 // --------------------------------------------------------------------------
129 // event tables and other macros for wxWidgets
130 // --------------------------------------------------------------------------
131
132 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
133 EVT_MENU(SERVER_QUIT, MyFrame::OnQuit)
134 EVT_MENU(SERVER_ABOUT, MyFrame::OnAbout)
135 EVT_MENU(SERVER_UDPTEST, MyFrame::OnUDPTest)
136 EVT_SOCKET(SERVER_ID, MyFrame::OnServerEvent)
137 EVT_SOCKET(SOCKET_ID, MyFrame::OnSocketEvent)
138 END_EVENT_TABLE()
139
140 IMPLEMENT_APP(MyApp)
141
142
143 // ==========================================================================
144 // implementation
145 // ==========================================================================
146
147 // --------------------------------------------------------------------------
148 // the application class
149 // --------------------------------------------------------------------------
150
151 bool MyApp::OnInit()
152 {
153 if ( !wxApp::OnInit() )
154 return false;
155
156 // Create the main application window
157 MyFrame *frame = new MyFrame();
158
159 // Show it and tell the application that it's our main window
160 frame->Show(true);
161 SetTopWindow(frame);
162
163 // Success
164 return true;
165 }
166
167 // --------------------------------------------------------------------------
168 // main frame
169 // --------------------------------------------------------------------------
170
171 // frame constructor
172
173 MyFrame::MyFrame() : wxFrame((wxFrame *)NULL, wxID_ANY,
174 _("wxSocket demo: Server"),
175 wxDefaultPosition, wxSize(300, 200))
176 {
177 // Give the frame an icon
178 SetIcon(wxICON(mondrian));
179
180 // Make menus
181 m_menuFile = new wxMenu();
182 m_menuFile->Append(SERVER_UDPTEST, "&UDP test\tCtrl-U");
183 m_menuFile->AppendSeparator();
184 m_menuFile->Append(SERVER_ABOUT, _("&About...\tCtrl-A"), _("Show about dialog"));
185 m_menuFile->AppendSeparator();
186 m_menuFile->Append(SERVER_QUIT, _("E&xit\tAlt-X"), _("Quit server"));
187
188 // Append menus to the menubar
189 m_menuBar = new wxMenuBar();
190 m_menuBar->Append(m_menuFile, _("&File"));
191 SetMenuBar(m_menuBar);
192
193 #if wxUSE_STATUSBAR
194 // Status bar
195 CreateStatusBar(2);
196 #endif // wxUSE_STATUSBAR
197
198 // Make a textctrl for logging
199 m_text = new wxTextCtrl(this, wxID_ANY,
200 _("Welcome to wxSocket demo: Server\n"),
201 wxDefaultPosition, wxDefaultSize,
202 wxTE_MULTILINE | wxTE_READONLY);
203 delete wxLog::SetActiveTarget(new wxLogTextCtrl(m_text));
204
205 // Create the address - defaults to localhost:0 initially
206 IPaddress addr;
207 addr.Service(3000);
208
209 wxLogMessage("Creating server at %s:%u", addr.IPAddress(), addr.Service());
210
211 // Create the socket
212 m_server = new wxSocketServer(addr);
213
214 // We use Ok() here to see if the server is really listening
215 if (! m_server->Ok())
216 {
217 wxLogMessage("Could not listen at the specified port !");
218 return;
219 }
220
221 IPaddress addrReal;
222 if ( !m_server->GetLocal(addrReal) )
223 wxLogMessage("ERROR: couldn't get the address we bound to");
224 else
225 wxLogMessage("Server listening at %s:%u",
226 addrReal.IPAddress(), addrReal.Service());
227
228 // Setup the event handler and subscribe to connection events
229 m_server->SetEventHandler(*this, SERVER_ID);
230 m_server->SetNotify(wxSOCKET_CONNECTION_FLAG);
231 m_server->Notify(true);
232
233 m_busy = false;
234 m_numClients = 0;
235 UpdateStatusBar();
236 }
237
238 MyFrame::~MyFrame()
239 {
240 // No delayed deletion here, as the frame is dying anyway
241 delete m_server;
242 }
243
244 // event handlers
245
246 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
247 {
248 // true is to force the frame to close
249 Close(true);
250 }
251
252 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
253 {
254 wxMessageBox(_("wxSocket demo: Server\n(c) 1999 Guillermo Rodriguez Garcia\n"),
255 _("About Server"),
256 wxOK | wxICON_INFORMATION, this);
257 }
258
259 void MyFrame::OnUDPTest(wxCommandEvent& WXUNUSED(event))
260 {
261 TestLogger logtest("UDP test");
262
263 IPaddress addr;
264 addr.Service(3000);
265 wxDatagramSocket sock(addr);
266
267 char buf[1024];
268 size_t n = sock.RecvFrom(addr, buf, sizeof(buf)).LastCount();
269 if ( !n )
270 {
271 wxLogMessage("ERROR: failed to receive data");
272 return;
273 }
274
275 wxLogMessage("Received \"%s\" from %s:%u.",
276 wxString::From8BitData(buf, n),
277 addr.IPAddress(), addr.Service());
278
279 for ( size_t i = 0; i < n; i++ )
280 {
281 char& c = buf[i];
282 if ( (c >= 'A' && c <= 'M') || (c >= 'a' && c <= 'm') )
283 c += 13;
284 else if ( (c >= 'N' && c <= 'Z') || (c >= 'n' && c <= 'z') )
285 c -= 13;
286 }
287
288 if ( sock.SendTo(addr, buf, n).LastCount() != n )
289 {
290 wxLogMessage("ERROR: failed to send data");
291 return;
292 }
293 }
294
295 void MyFrame::Test1(wxSocketBase *sock)
296 {
297 TestLogger logtest("Test 1");
298
299 // Receive data from socket and send it back. We will first
300 // get a byte with the buffer size, so we can specify the
301 // exact size and use the wxSOCKET_WAITALL flag. Also, we
302 // disabled input events so we won't have unwanted reentrance.
303 // This way we can avoid the infamous wxSOCKET_BLOCK flag.
304
305 sock->SetFlags(wxSOCKET_WAITALL);
306
307 // Read the size
308 unsigned char len;
309 sock->Read(&len, 1);
310 wxCharBuffer buf(len);
311
312 // Read the data
313 sock->Read(buf.data(), len);
314 wxLogMessage("Got the data, sending it back");
315
316 // Write it back
317 sock->Write(buf, len);
318 }
319
320 void MyFrame::Test2(wxSocketBase *sock)
321 {
322 char buf[4096];
323
324 TestLogger logtest("Test 2");
325
326 // We don't need to set flags because ReadMsg and WriteMsg
327 // are not affected by them anyway.
328
329 // Read the message
330 wxUint32 len = sock->ReadMsg(buf, sizeof(buf)).LastCount();
331 if ( !len )
332 {
333 wxLogError("Failed to read message.");
334 return;
335 }
336
337 wxLogMessage("Got \"%s\" from client.", wxString::FromUTF8(buf, len));
338 wxLogMessage("Sending the data back");
339
340 // Write it back
341 sock->WriteMsg(buf, len);
342 }
343
344 void MyFrame::Test3(wxSocketBase *sock)
345 {
346 TestLogger logtest("Test 3");
347
348 // This test is similar to the first one, but the len is
349 // expressed in kbytes - this tests large data transfers.
350
351 sock->SetFlags(wxSOCKET_WAITALL);
352
353 // Read the size
354 unsigned char len;
355 sock->Read(&len, 1);
356 wxCharBuffer buf(len*1024);
357
358 // Read the data
359 sock->Read(buf.data(), len * 1024);
360 wxLogMessage("Got the data, sending it back");
361
362 // Write it back
363 sock->Write(buf, len * 1024);
364 }
365
366 void MyFrame::OnServerEvent(wxSocketEvent& event)
367 {
368 wxString s = _("OnServerEvent: ");
369 wxSocketBase *sock;
370
371 switch(event.GetSocketEvent())
372 {
373 case wxSOCKET_CONNECTION : s.Append(_("wxSOCKET_CONNECTION\n")); break;
374 default : s.Append(_("Unexpected event !\n")); break;
375 }
376
377 m_text->AppendText(s);
378
379 // Accept new connection if there is one in the pending
380 // connections queue, else exit. We use Accept(false) for
381 // non-blocking accept (although if we got here, there
382 // should ALWAYS be a pending connection).
383
384 sock = m_server->Accept(false);
385
386 if (sock)
387 {
388 IPaddress addr;
389 if ( !sock->GetPeer(addr) )
390 wxLogMessage("New connection from unknown client accepted.");
391 else
392 wxLogMessage("New client connection from %s:%u accepted",
393 addr.IPAddress(), addr.Service());
394 }
395 else
396 {
397 wxLogMessage("Error: couldn't accept a new connection");
398 return;
399 }
400
401 sock->SetEventHandler(*this, SOCKET_ID);
402 sock->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
403 sock->Notify(true);
404
405 m_numClients++;
406 UpdateStatusBar();
407 }
408
409 void MyFrame::OnSocketEvent(wxSocketEvent& event)
410 {
411 wxString s = _("OnSocketEvent: ");
412 wxSocketBase *sock = event.GetSocket();
413
414 // First, print a message
415 switch(event.GetSocketEvent())
416 {
417 case wxSOCKET_INPUT : s.Append(_("wxSOCKET_INPUT\n")); break;
418 case wxSOCKET_LOST : s.Append(_("wxSOCKET_LOST\n")); break;
419 default : s.Append(_("Unexpected event !\n")); break;
420 }
421
422 m_text->AppendText(s);
423
424 // Now we process the event
425 switch(event.GetSocketEvent())
426 {
427 case wxSOCKET_INPUT:
428 {
429 // We disable input events, so that the test doesn't trigger
430 // wxSocketEvent again.
431 sock->SetNotify(wxSOCKET_LOST_FLAG);
432
433 // Which test are we going to run?
434 unsigned char c;
435 sock->Read(&c, 1);
436
437 switch (c)
438 {
439 case 0xBE: Test1(sock); break;
440 case 0xCE: Test2(sock); break;
441 case 0xDE: Test3(sock); break;
442 default:
443 wxLogMessage("Unknown test id received from client");
444 }
445
446 // Enable input events again.
447 sock->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG);
448 break;
449 }
450 case wxSOCKET_LOST:
451 {
452 m_numClients--;
453
454 // Destroy() should be used instead of delete wherever possible,
455 // due to the fact that wxSocket uses 'delayed events' (see the
456 // documentation for wxPostEvent) and we don't want an event to
457 // arrive to the event handler (the frame, here) after the socket
458 // has been deleted. Also, we might be doing some other thing with
459 // the socket at the same time; for example, we might be in the
460 // middle of a test or something. Destroy() takes care of all
461 // this for us.
462
463 wxLogMessage("Deleting socket.");
464 sock->Destroy();
465 break;
466 }
467 default: ;
468 }
469
470 UpdateStatusBar();
471 }
472
473 // convenience functions
474
475 void MyFrame::UpdateStatusBar()
476 {
477 #if wxUSE_STATUSBAR
478 wxString s;
479 s.Printf(_("%d clients connected"), m_numClients);
480 SetStatusText(s, 1);
481 #endif // wxUSE_STATUSBAR
482 }