]> git.saurik.com Git - wxWidgets.git/blame - samples/sockets/server.cpp
added wakeup implementation for osx_cocoa
[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) )
43b2d5e7 223 {
afeeb04d 224 wxLogMessage("ERROR: couldn't get the address we bound to");
43b2d5e7 225 }
f85d901f 226 else
43b2d5e7 227 {
afeeb04d
VZ
228 wxLogMessage("Server listening at %s:%u",
229 addrReal.IPAddress(), addrReal.Service());
43b2d5e7 230 }
bd4d918f
GRG
231
232 // Setup the event handler and subscribe to connection events
233 m_server->SetEventHandler(*this, SERVER_ID);
234 m_server->SetNotify(wxSOCKET_CONNECTION_FLAG);
b62ca03d 235 m_server->Notify(true);
f85d901f 236
b62ca03d 237 m_busy = false;
f85d901f
GRG
238 m_numClients = 0;
239 UpdateStatusBar();
f4ada568
GL
240}
241
f85d901f 242MyFrame::~MyFrame()
f4ada568 243{
bd4d918f 244 // No delayed deletion here, as the frame is dying anyway
f85d901f
GRG
245 delete m_server;
246}
f4ada568 247
f85d901f 248// event handlers
f4ada568 249
f85d901f
GRG
250void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
251{
b62ca03d
WS
252 // true is to force the frame to close
253 Close(true);
f85d901f 254}
f4ada568 255
f85d901f
GRG
256void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
257{
4693b20c 258 wxMessageBox(_("wxSocket demo: Server\n(c) 1999 Guillermo Rodriguez Garcia\n"),
bd4d918f 259 _("About Server"),
f85d901f 260 wxOK | wxICON_INFORMATION, this);
f4ada568
GL
261}
262
46b11427
VZ
263void MyFrame::OnUDPTest(wxCommandEvent& WXUNUSED(event))
264{
265 TestLogger logtest("UDP test");
266
267 IPaddress addr;
268 addr.Service(3000);
269 wxDatagramSocket sock(addr);
270
271 char buf[1024];
272 size_t n = sock.RecvFrom(addr, buf, sizeof(buf)).LastCount();
273 if ( !n )
274 {
275 wxLogMessage("ERROR: failed to receive data");
276 return;
277 }
278
279 wxLogMessage("Received \"%s\" from %s:%u.",
280 wxString::From8BitData(buf, n),
281 addr.IPAddress(), addr.Service());
282
283 for ( size_t i = 0; i < n; i++ )
284 {
285 char& c = buf[i];
286 if ( (c >= 'A' && c <= 'M') || (c >= 'a' && c <= 'm') )
287 c += 13;
288 else if ( (c >= 'N' && c <= 'Z') || (c >= 'n' && c <= 'z') )
289 c -= 13;
290 }
291
292 if ( sock.SendTo(addr, buf, n).LastCount() != n )
293 {
294 wxLogMessage("ERROR: failed to send data");
295 return;
296 }
297}
298
f85d901f 299void MyFrame::Test1(wxSocketBase *sock)
f4ada568 300{
38418fde 301 TestLogger logtest("Test 1");
f4ada568 302
f85d901f
GRG
303 // Receive data from socket and send it back. We will first
304 // get a byte with the buffer size, so we can specify the
6097c3a2
GRG
305 // exact size and use the wxSOCKET_WAITALL flag. Also, we
306 // disabled input events so we won't have unwanted reentrance.
307 // This way we can avoid the infamous wxSOCKET_BLOCK flag.
e51b0130 308
f85d901f
GRG
309 sock->SetFlags(wxSOCKET_WAITALL);
310
bc7e88ae 311 // Read the size
38418fde 312 unsigned char len;
f187448d 313 sock->Read(&len, 1);
38418fde 314 wxCharBuffer buf(len);
bc7e88ae
GRG
315
316 // Read the data
38418fde
VZ
317 sock->Read(buf.data(), len);
318 wxLogMessage("Got the data, sending it back");
bc7e88ae
GRG
319
320 // Write it back
f85d901f 321 sock->Write(buf, len);
f4ada568
GL
322}
323
f85d901f 324void MyFrame::Test2(wxSocketBase *sock)
f4ada568 325{
38418fde 326 char buf[4096];
f85d901f 327
38418fde 328 TestLogger logtest("Test 2");
f85d901f
GRG
329
330 // We don't need to set flags because ReadMsg and WriteMsg
331 // are not affected by them anyway.
e51b0130 332
bc7e88ae 333 // Read the message
38418fde
VZ
334 wxUint32 len = sock->ReadMsg(buf, sizeof(buf)).LastCount();
335 if ( !len )
336 {
337 wxLogError("Failed to read message.");
338 return;
339 }
340
341 wxLogMessage("Got \"%s\" from client.", wxString::FromUTF8(buf, len));
342 wxLogMessage("Sending the data back");
f85d901f 343
bc7e88ae 344 // Write it back
f85d901f 345 sock->WriteMsg(buf, len);
f4ada568
GL
346}
347
f85d901f 348void MyFrame::Test3(wxSocketBase *sock)
f4ada568 349{
38418fde 350 TestLogger logtest("Test 3");
6097c3a2 351
677a9f0c 352 // This test is similar to the first one, but the len is
6097c3a2 353 // expressed in kbytes - this tests large data transfers.
e51b0130 354
6097c3a2
GRG
355 sock->SetFlags(wxSOCKET_WAITALL);
356
bc7e88ae 357 // Read the size
38418fde 358 unsigned char len;
f187448d 359 sock->Read(&len, 1);
38418fde 360 wxCharBuffer buf(len*1024);
bc7e88ae
GRG
361
362 // Read the data
38418fde
VZ
363 sock->Read(buf.data(), len * 1024);
364 wxLogMessage("Got the data, sending it back");
bc7e88ae
GRG
365
366 // Write it back
6097c3a2 367 sock->Write(buf, len * 1024);
f4ada568
GL
368}
369
f85d901f 370void MyFrame::OnServerEvent(wxSocketEvent& event)
f4ada568 371{
bd4d918f 372 wxString s = _("OnServerEvent: ");
f85d901f
GRG
373 wxSocketBase *sock;
374
bc7e88ae 375 switch(event.GetSocketEvent())
f85d901f 376 {
bd4d918f
GRG
377 case wxSOCKET_CONNECTION : s.Append(_("wxSOCKET_CONNECTION\n")); break;
378 default : s.Append(_("Unexpected event !\n")); break;
f85d901f 379 }
f4ada568 380
f85d901f 381 m_text->AppendText(s);
765e386b 382
f85d901f 383 // Accept new connection if there is one in the pending
b62ca03d 384 // connections queue, else exit. We use Accept(false) for
f85d901f
GRG
385 // non-blocking accept (although if we got here, there
386 // should ALWAYS be a pending connection).
e51b0130 387
b62ca03d 388 sock = m_server->Accept(false);
f85d901f
GRG
389
390 if (sock)
391 {
afeeb04d
VZ
392 IPaddress addr;
393 if ( !sock->GetPeer(addr) )
43b2d5e7 394 {
afeeb04d 395 wxLogMessage("New connection from unknown client accepted.");
43b2d5e7 396 }
afeeb04d 397 else
43b2d5e7 398 {
afeeb04d
VZ
399 wxLogMessage("New client connection from %s:%u accepted",
400 addr.IPAddress(), addr.Service());
43b2d5e7 401 }
f85d901f
GRG
402 }
403 else
404 {
38418fde 405 wxLogMessage("Error: couldn't accept a new connection");
f85d901f
GRG
406 return;
407 }
408
409 sock->SetEventHandler(*this, SOCKET_ID);
410 sock->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
b62ca03d 411 sock->Notify(true);
f85d901f
GRG
412
413 m_numClients++;
414 UpdateStatusBar();
f4ada568
GL
415}
416
f85d901f
GRG
417void MyFrame::OnSocketEvent(wxSocketEvent& event)
418{
bd4d918f 419 wxString s = _("OnSocketEvent: ");
f4d5e009 420 wxSocketBase *sock = event.GetSocket();
f85d901f 421
f4d5e009 422 // First, print a message
bc7e88ae 423 switch(event.GetSocketEvent())
f85d901f 424 {
f4d5e009
GRG
425 case wxSOCKET_INPUT : s.Append(_("wxSOCKET_INPUT\n")); break;
426 case wxSOCKET_LOST : s.Append(_("wxSOCKET_LOST\n")); break;
427 default : s.Append(_("Unexpected event !\n")); break;
f85d901f
GRG
428 }
429
430 m_text->AppendText(s);
431
432 // Now we process the event
bc7e88ae 433 switch(event.GetSocketEvent())
f85d901f
GRG
434 {
435 case wxSOCKET_INPUT:
436 {
437 // We disable input events, so that the test doesn't trigger
438 // wxSocketEvent again.
439 sock->SetNotify(wxSOCKET_LOST_FLAG);
440
441 // Which test are we going to run?
442 unsigned char c;
f4d5e009 443 sock->Read(&c, 1);
f85d901f
GRG
444
445 switch (c)
446 {
447 case 0xBE: Test1(sock); break;
448 case 0xCE: Test2(sock); break;
449 case 0xDE: Test3(sock); break;
f4d5e009 450 default:
38418fde 451 wxLogMessage("Unknown test id received from client");
f85d901f
GRG
452 }
453
454 // Enable input events again.
455 sock->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG);
456 break;
457 }
458 case wxSOCKET_LOST:
459 {
460 m_numClients--;
461
bd4d918f
GRG
462 // Destroy() should be used instead of delete wherever possible,
463 // due to the fact that wxSocket uses 'delayed events' (see the
464 // documentation for wxPostEvent) and we don't want an event to
465 // arrive to the event handler (the frame, here) after the socket
466 // has been deleted. Also, we might be doing some other thing with
467 // the socket at the same time; for example, we might be in the
468 // middle of a test or something. Destroy() takes care of all
bc7e88ae 469 // this for us.
bd4d918f 470
38418fde 471 wxLogMessage("Deleting socket.");
bd4d918f 472 sock->Destroy();
f85d901f
GRG
473 break;
474 }
475 default: ;
476 }
477
478 UpdateStatusBar();
479}
480
481// convenience functions
482
483void MyFrame::UpdateStatusBar()
f4ada568 484{
8520f137 485#if wxUSE_STATUSBAR
f85d901f 486 wxString s;
bd4d918f 487 s.Printf(_("%d clients connected"), m_numClients);
f85d901f 488 SetStatusText(s, 1);
8520f137 489#endif // wxUSE_STATUSBAR
f4ada568 490}