]> git.saurik.com Git - wxWidgets.git/blob - samples/sockets/server.cpp
Have DoRemoveFromSelection() take active editor into account
[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 {
224 wxLogMessage("ERROR: couldn't get the address we bound to");
225 }
226 else
227 {
228 wxLogMessage("Server listening at %s:%u",
229 addrReal.IPAddress(), addrReal.Service());
230 }
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);
235 m_server->Notify(true);
236
237 m_busy = false;
238 m_numClients = 0;
239 UpdateStatusBar();
240 }
241
242 MyFrame::~MyFrame()
243 {
244 // No delayed deletion here, as the frame is dying anyway
245 delete m_server;
246 }
247
248 // event handlers
249
250 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
251 {
252 // true is to force the frame to close
253 Close(true);
254 }
255
256 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
257 {
258 wxMessageBox(_("wxSocket demo: Server\n(c) 1999 Guillermo Rodriguez Garcia\n"),
259 _("About Server"),
260 wxOK | wxICON_INFORMATION, this);
261 }
262
263 void 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
299 void MyFrame::Test1(wxSocketBase *sock)
300 {
301 TestLogger logtest("Test 1");
302
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
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.
308
309 sock->SetFlags(wxSOCKET_WAITALL);
310
311 // Read the size
312 unsigned char len;
313 sock->Read(&len, 1);
314 wxCharBuffer buf(len);
315
316 // Read the data
317 sock->Read(buf.data(), len);
318 wxLogMessage("Got the data, sending it back");
319
320 // Write it back
321 sock->Write(buf, len);
322 }
323
324 void MyFrame::Test2(wxSocketBase *sock)
325 {
326 char buf[4096];
327
328 TestLogger logtest("Test 2");
329
330 // We don't need to set flags because ReadMsg and WriteMsg
331 // are not affected by them anyway.
332
333 // Read the message
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");
343
344 // Write it back
345 sock->WriteMsg(buf, len);
346 }
347
348 void MyFrame::Test3(wxSocketBase *sock)
349 {
350 TestLogger logtest("Test 3");
351
352 // This test is similar to the first one, but the len is
353 // expressed in kbytes - this tests large data transfers.
354
355 sock->SetFlags(wxSOCKET_WAITALL);
356
357 // Read the size
358 unsigned char len;
359 sock->Read(&len, 1);
360 wxCharBuffer buf(len*1024);
361
362 // Read the data
363 sock->Read(buf.data(), len * 1024);
364 wxLogMessage("Got the data, sending it back");
365
366 // Write it back
367 sock->Write(buf, len * 1024);
368 }
369
370 void MyFrame::OnServerEvent(wxSocketEvent& event)
371 {
372 wxString s = _("OnServerEvent: ");
373 wxSocketBase *sock;
374
375 switch(event.GetSocketEvent())
376 {
377 case wxSOCKET_CONNECTION : s.Append(_("wxSOCKET_CONNECTION\n")); break;
378 default : s.Append(_("Unexpected event !\n")); break;
379 }
380
381 m_text->AppendText(s);
382
383 // Accept new connection if there is one in the pending
384 // connections queue, else exit. We use Accept(false) for
385 // non-blocking accept (although if we got here, there
386 // should ALWAYS be a pending connection).
387
388 sock = m_server->Accept(false);
389
390 if (sock)
391 {
392 IPaddress addr;
393 if ( !sock->GetPeer(addr) )
394 {
395 wxLogMessage("New connection from unknown client accepted.");
396 }
397 else
398 {
399 wxLogMessage("New client connection from %s:%u accepted",
400 addr.IPAddress(), addr.Service());
401 }
402 }
403 else
404 {
405 wxLogMessage("Error: couldn't accept a new connection");
406 return;
407 }
408
409 sock->SetEventHandler(*this, SOCKET_ID);
410 sock->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
411 sock->Notify(true);
412
413 m_numClients++;
414 UpdateStatusBar();
415 }
416
417 void MyFrame::OnSocketEvent(wxSocketEvent& event)
418 {
419 wxString s = _("OnSocketEvent: ");
420 wxSocketBase *sock = event.GetSocket();
421
422 // First, print a message
423 switch(event.GetSocketEvent())
424 {
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;
428 }
429
430 m_text->AppendText(s);
431
432 // Now we process the event
433 switch(event.GetSocketEvent())
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;
443 sock->Read(&c, 1);
444
445 switch (c)
446 {
447 case 0xBE: Test1(sock); break;
448 case 0xCE: Test2(sock); break;
449 case 0xDE: Test3(sock); break;
450 default:
451 wxLogMessage("Unknown test id received from client");
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
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
469 // this for us.
470
471 wxLogMessage("Deleting socket.");
472 sock->Destroy();
473 break;
474 }
475 default: ;
476 }
477
478 UpdateStatusBar();
479 }
480
481 // convenience functions
482
483 void MyFrame::UpdateStatusBar()
484 {
485 #if wxUSE_STATUSBAR
486 wxString s;
487 s.Printf(_("%d clients connected"), m_numClients);
488 SetStatusText(s, 1);
489 #endif // wxUSE_STATUSBAR
490 }