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