]> git.saurik.com Git - wxWidgets.git/blame - samples/sockets/server.cpp
include wx/arrstr.h as it's needed by wxImageHandler and may not be implicitly includ...
[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>
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// --------------------------------------------------------------------------
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
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
2804f77d 47#include "mondrian.xpm"
e2a6f233 48
f85d901f
GRG
49// --------------------------------------------------------------------------
50// classes
51// --------------------------------------------------------------------------
52
f4ada568 53// Define a new application type
f85d901f
GRG
54class MyApp : public wxApp
55{
56public:
57 virtual bool OnInit();
f4ada568
GL
58};
59
f85d901f
GRG
60// Define a new frame type: this is going to be our main frame
61class MyFrame : public wxFrame
62{
f4ada568 63public:
f85d901f
GRG
64 MyFrame();
65 ~MyFrame();
66
67 // event handlers (these functions should _not_ be virtual)
46b11427 68 void OnUDPTest(wxCommandEvent& event);
f85d901f
GRG
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
81private:
82 wxSocketServer *m_server;
f85d901f
GRG
83 wxTextCtrl *m_text;
84 wxMenu *m_menuFile;
85 wxMenuBar *m_menuBar;
86 bool m_busy;
87 int m_numClients;
88
be5a51fb 89 // any class wishing to process wxWidgets events must use this macro
f85d901f
GRG
90 DECLARE_EVENT_TABLE()
91};
92
38418fde
VZ
93// simple helper class to log start and end of each test
94class TestLogger
95{
96public:
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
107private:
108 const wxString m_name;
109};
110
f85d901f
GRG
111// --------------------------------------------------------------------------
112// constants
113// --------------------------------------------------------------------------
114
115// IDs for the controls and the menu commands
116enum
117{
118 // menu items
46b11427 119 SERVER_UDPTEST = 10,
91b07357
JS
120 SERVER_QUIT = wxID_EXIT,
121 SERVER_ABOUT = wxID_ABOUT,
f85d901f
GRG
122
123 // id for sockets
91b07357 124 SERVER_ID = 100,
f85d901f 125 SOCKET_ID
f4ada568
GL
126};
127
f85d901f 128// --------------------------------------------------------------------------
be5a51fb 129// event tables and other macros for wxWidgets
f85d901f 130// --------------------------------------------------------------------------
f4ada568
GL
131
132BEGIN_EVENT_TABLE(MyFrame, wxFrame)
f85d901f
GRG
133 EVT_MENU(SERVER_QUIT, MyFrame::OnQuit)
134 EVT_MENU(SERVER_ABOUT, MyFrame::OnAbout)
46b11427 135 EVT_MENU(SERVER_UDPTEST, MyFrame::OnUDPTest)
f85d901f
GRG
136 EVT_SOCKET(SERVER_ID, MyFrame::OnServerEvent)
137 EVT_SOCKET(SOCKET_ID, MyFrame::OnSocketEvent)
f4ada568
GL
138END_EVENT_TABLE()
139
f4ada568
GL
140IMPLEMENT_APP(MyApp)
141
f4ada568 142
f85d901f
GRG
143// ==========================================================================
144// implementation
145// ==========================================================================
f4ada568 146
f85d901f
GRG
147// --------------------------------------------------------------------------
148// the application class
149// --------------------------------------------------------------------------
f4ada568 150
f85d901f
GRG
151bool MyApp::OnInit()
152{
45e6e6f8
VZ
153 if ( !wxApp::OnInit() )
154 return false;
155
f85d901f
GRG
156 // Create the main application window
157 MyFrame *frame = new MyFrame();
f4ada568 158
f85d901f 159 // Show it and tell the application that it's our main window
b62ca03d 160 frame->Show(true);
f85d901f 161 SetTopWindow(frame);
2b98cb1f 162
bd4d918f 163 // Success
b62ca03d 164 return true;
f4ada568
GL
165}
166
f85d901f
GRG
167// --------------------------------------------------------------------------
168// main frame
169// --------------------------------------------------------------------------
a737331d 170
f85d901f 171// frame constructor
bd4d918f 172
b62ca03d 173MyFrame::MyFrame() : wxFrame((wxFrame *)NULL, wxID_ANY,
bd4d918f 174 _("wxSocket demo: Server"),
f85d901f 175 wxDefaultPosition, wxSize(300, 200))
f4ada568 176{
f85d901f
GRG
177 // Give the frame an icon
178 SetIcon(wxICON(mondrian));
179
180 // Make menus
181 m_menuFile = new wxMenu();
46b11427
VZ
182 m_menuFile->Append(SERVER_UDPTEST, "&UDP test\tCtrl-U");
183 m_menuFile->AppendSeparator();
bd4d918f 184 m_menuFile->Append(SERVER_ABOUT, _("&About...\tCtrl-A"), _("Show about dialog"));
f85d901f 185 m_menuFile->AppendSeparator();
bd4d918f 186 m_menuFile->Append(SERVER_QUIT, _("E&xit\tAlt-X"), _("Quit server"));
f85d901f
GRG
187
188 // Append menus to the menubar
189 m_menuBar = new wxMenuBar();
bd4d918f 190 m_menuBar->Append(m_menuFile, _("&File"));
f85d901f
GRG
191 SetMenuBar(m_menuBar);
192
8520f137 193#if wxUSE_STATUSBAR
f85d901f
GRG
194 // Status bar
195 CreateStatusBar(2);
8520f137 196#endif // wxUSE_STATUSBAR
f85d901f 197
bd4d918f 198 // Make a textctrl for logging
b62ca03d 199 m_text = new wxTextCtrl(this, wxID_ANY,
bd4d918f
GRG
200 _("Welcome to wxSocket demo: Server\n"),
201 wxDefaultPosition, wxDefaultSize,
f85d901f 202 wxTE_MULTILINE | wxTE_READONLY);
38418fde 203 delete wxLog::SetActiveTarget(new wxLogTextCtrl(m_text));
f85d901f 204
bd4d918f 205 // Create the address - defaults to localhost:0 initially
afeeb04d 206 IPaddress addr;
f85d901f
GRG
207 addr.Service(3000);
208
afeeb04d
VZ
209 wxLogMessage("Creating server at %s:%u", addr.IPAddress(), addr.Service());
210
bd4d918f 211 // Create the socket
f85d901f 212 m_server = new wxSocketServer(addr);
f85d901f
GRG
213
214 // We use Ok() here to see if the server is really listening
bd4d918f
GRG
215 if (! m_server->Ok())
216 {
38418fde 217 wxLogMessage("Could not listen at the specified port !");
bd4d918f
GRG
218 return;
219 }
afeeb04d
VZ
220
221 IPaddress addrReal;
222 if ( !m_server->GetLocal(addrReal) )
223 wxLogMessage("ERROR: couldn't get the address we bound to");
f85d901f 224 else
afeeb04d
VZ
225 wxLogMessage("Server listening at %s:%u",
226 addrReal.IPAddress(), addrReal.Service());
bd4d918f
GRG
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);
b62ca03d 231 m_server->Notify(true);
f85d901f 232
b62ca03d 233 m_busy = false;
f85d901f
GRG
234 m_numClients = 0;
235 UpdateStatusBar();
f4ada568
GL
236}
237
f85d901f 238MyFrame::~MyFrame()
f4ada568 239{
bd4d918f 240 // No delayed deletion here, as the frame is dying anyway
f85d901f
GRG
241 delete m_server;
242}
f4ada568 243
f85d901f 244// event handlers
f4ada568 245
f85d901f
GRG
246void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
247{
b62ca03d
WS
248 // true is to force the frame to close
249 Close(true);
f85d901f 250}
f4ada568 251
f85d901f
GRG
252void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
253{
4693b20c 254 wxMessageBox(_("wxSocket demo: Server\n(c) 1999 Guillermo Rodriguez Garcia\n"),
bd4d918f 255 _("About Server"),
f85d901f 256 wxOK | wxICON_INFORMATION, this);
f4ada568
GL
257}
258
46b11427
VZ
259void 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
f85d901f 295void MyFrame::Test1(wxSocketBase *sock)
f4ada568 296{
38418fde 297 TestLogger logtest("Test 1");
f4ada568 298
f85d901f
GRG
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
6097c3a2
GRG
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.
e51b0130 304
f85d901f
GRG
305 sock->SetFlags(wxSOCKET_WAITALL);
306
bc7e88ae 307 // Read the size
38418fde 308 unsigned char len;
f187448d 309 sock->Read(&len, 1);
38418fde 310 wxCharBuffer buf(len);
bc7e88ae
GRG
311
312 // Read the data
38418fde
VZ
313 sock->Read(buf.data(), len);
314 wxLogMessage("Got the data, sending it back");
bc7e88ae
GRG
315
316 // Write it back
f85d901f 317 sock->Write(buf, len);
f4ada568
GL
318}
319
f85d901f 320void MyFrame::Test2(wxSocketBase *sock)
f4ada568 321{
38418fde 322 char buf[4096];
f85d901f 323
38418fde 324 TestLogger logtest("Test 2");
f85d901f
GRG
325
326 // We don't need to set flags because ReadMsg and WriteMsg
327 // are not affected by them anyway.
e51b0130 328
bc7e88ae 329 // Read the message
38418fde
VZ
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");
f85d901f 339
bc7e88ae 340 // Write it back
f85d901f 341 sock->WriteMsg(buf, len);
f4ada568
GL
342}
343
f85d901f 344void MyFrame::Test3(wxSocketBase *sock)
f4ada568 345{
38418fde 346 TestLogger logtest("Test 3");
6097c3a2 347
677a9f0c 348 // This test is similar to the first one, but the len is
6097c3a2 349 // expressed in kbytes - this tests large data transfers.
e51b0130 350
6097c3a2
GRG
351 sock->SetFlags(wxSOCKET_WAITALL);
352
bc7e88ae 353 // Read the size
38418fde 354 unsigned char len;
f187448d 355 sock->Read(&len, 1);
38418fde 356 wxCharBuffer buf(len*1024);
bc7e88ae
GRG
357
358 // Read the data
38418fde
VZ
359 sock->Read(buf.data(), len * 1024);
360 wxLogMessage("Got the data, sending it back");
bc7e88ae
GRG
361
362 // Write it back
6097c3a2 363 sock->Write(buf, len * 1024);
f4ada568
GL
364}
365
f85d901f 366void MyFrame::OnServerEvent(wxSocketEvent& event)
f4ada568 367{
bd4d918f 368 wxString s = _("OnServerEvent: ");
f85d901f
GRG
369 wxSocketBase *sock;
370
bc7e88ae 371 switch(event.GetSocketEvent())
f85d901f 372 {
bd4d918f
GRG
373 case wxSOCKET_CONNECTION : s.Append(_("wxSOCKET_CONNECTION\n")); break;
374 default : s.Append(_("Unexpected event !\n")); break;
f85d901f 375 }
f4ada568 376
f85d901f 377 m_text->AppendText(s);
765e386b 378
f85d901f 379 // Accept new connection if there is one in the pending
b62ca03d 380 // connections queue, else exit. We use Accept(false) for
f85d901f
GRG
381 // non-blocking accept (although if we got here, there
382 // should ALWAYS be a pending connection).
e51b0130 383
b62ca03d 384 sock = m_server->Accept(false);
f85d901f
GRG
385
386 if (sock)
387 {
afeeb04d
VZ
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());
f85d901f
GRG
394 }
395 else
396 {
38418fde 397 wxLogMessage("Error: couldn't accept a new connection");
f85d901f
GRG
398 return;
399 }
400
401 sock->SetEventHandler(*this, SOCKET_ID);
402 sock->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
b62ca03d 403 sock->Notify(true);
f85d901f
GRG
404
405 m_numClients++;
406 UpdateStatusBar();
f4ada568
GL
407}
408
f85d901f
GRG
409void MyFrame::OnSocketEvent(wxSocketEvent& event)
410{
bd4d918f 411 wxString s = _("OnSocketEvent: ");
f4d5e009 412 wxSocketBase *sock = event.GetSocket();
f85d901f 413
f4d5e009 414 // First, print a message
bc7e88ae 415 switch(event.GetSocketEvent())
f85d901f 416 {
f4d5e009
GRG
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;
f85d901f
GRG
420 }
421
422 m_text->AppendText(s);
423
424 // Now we process the event
bc7e88ae 425 switch(event.GetSocketEvent())
f85d901f
GRG
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;
f4d5e009 435 sock->Read(&c, 1);
f85d901f
GRG
436
437 switch (c)
438 {
439 case 0xBE: Test1(sock); break;
440 case 0xCE: Test2(sock); break;
441 case 0xDE: Test3(sock); break;
f4d5e009 442 default:
38418fde 443 wxLogMessage("Unknown test id received from client");
f85d901f
GRG
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
bd4d918f
GRG
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
bc7e88ae 461 // this for us.
bd4d918f 462
38418fde 463 wxLogMessage("Deleting socket.");
bd4d918f 464 sock->Destroy();
f85d901f
GRG
465 break;
466 }
467 default: ;
468 }
469
470 UpdateStatusBar();
471}
472
473// convenience functions
474
475void MyFrame::UpdateStatusBar()
f4ada568 476{
8520f137 477#if wxUSE_STATUSBAR
f85d901f 478 wxString s;
bd4d918f 479 s.Printf(_("%d clients connected"), m_numClients);
f85d901f 480 SetStatusText(s, 1);
8520f137 481#endif // wxUSE_STATUSBAR
f4ada568 482}