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