show the string received from client in test 2 correctly; use TestLogger just as...
[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 // --------------------------------------------------------------------------
35 // resources
36 // --------------------------------------------------------------------------
37
38 // the application icon
39 #include "mondrian.xpm"
40
41 // --------------------------------------------------------------------------
42 // classes
43 // --------------------------------------------------------------------------
44
45 // Define a new application type
46 class MyApp : public wxApp
47 {
48 public:
49 virtual bool OnInit();
50 };
51
52 // Define a new frame type: this is going to be our main frame
53 class MyFrame : public wxFrame
54 {
55 public:
56 MyFrame();
57 ~MyFrame();
58
59 // event handlers (these functions should _not_ be virtual)
60 void OnQuit(wxCommandEvent& event);
61 void OnAbout(wxCommandEvent& event);
62 void OnServerEvent(wxSocketEvent& event);
63 void OnSocketEvent(wxSocketEvent& event);
64
65 void Test1(wxSocketBase *sock);
66 void Test2(wxSocketBase *sock);
67 void Test3(wxSocketBase *sock);
68
69 // convenience functions
70 void UpdateStatusBar();
71
72 private:
73 wxSocketServer *m_server;
74 wxTextCtrl *m_text;
75 wxMenu *m_menuFile;
76 wxMenuBar *m_menuBar;
77 bool m_busy;
78 int m_numClients;
79
80 // any class wishing to process wxWidgets events must use this macro
81 DECLARE_EVENT_TABLE()
82 };
83
84 // simple helper class to log start and end of each test
85 class TestLogger
86 {
87 public:
88 TestLogger(const wxString& name) : m_name(name)
89 {
90 wxLogMessage("=== %s begins ===", m_name);
91 }
92
93 ~TestLogger()
94 {
95 wxLogMessage("=== %s ends ===", m_name);
96 }
97
98 private:
99 const wxString m_name;
100 };
101
102 // --------------------------------------------------------------------------
103 // constants
104 // --------------------------------------------------------------------------
105
106 // IDs for the controls and the menu commands
107 enum
108 {
109 // menu items
110 SERVER_QUIT = wxID_EXIT,
111 SERVER_ABOUT = wxID_ABOUT,
112
113 // id for sockets
114 SERVER_ID = 100,
115 SOCKET_ID
116 };
117
118 // --------------------------------------------------------------------------
119 // event tables and other macros for wxWidgets
120 // --------------------------------------------------------------------------
121
122 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
123 EVT_MENU(SERVER_QUIT, MyFrame::OnQuit)
124 EVT_MENU(SERVER_ABOUT, MyFrame::OnAbout)
125 EVT_SOCKET(SERVER_ID, MyFrame::OnServerEvent)
126 EVT_SOCKET(SOCKET_ID, MyFrame::OnSocketEvent)
127 END_EVENT_TABLE()
128
129 IMPLEMENT_APP(MyApp)
130
131
132 // ==========================================================================
133 // implementation
134 // ==========================================================================
135
136 // --------------------------------------------------------------------------
137 // the application class
138 // --------------------------------------------------------------------------
139
140 bool MyApp::OnInit()
141 {
142 if ( !wxApp::OnInit() )
143 return false;
144
145 // Create the main application window
146 MyFrame *frame = new MyFrame();
147
148 // Show it and tell the application that it's our main window
149 frame->Show(true);
150 SetTopWindow(frame);
151
152 // Success
153 return true;
154 }
155
156 // --------------------------------------------------------------------------
157 // main frame
158 // --------------------------------------------------------------------------
159
160 // frame constructor
161
162 MyFrame::MyFrame() : wxFrame((wxFrame *)NULL, wxID_ANY,
163 _("wxSocket demo: Server"),
164 wxDefaultPosition, wxSize(300, 200))
165 {
166 // Give the frame an icon
167 SetIcon(wxICON(mondrian));
168
169 // Make menus
170 m_menuFile = new wxMenu();
171 m_menuFile->Append(SERVER_ABOUT, _("&About...\tCtrl-A"), _("Show about dialog"));
172 m_menuFile->AppendSeparator();
173 m_menuFile->Append(SERVER_QUIT, _("E&xit\tAlt-X"), _("Quit server"));
174
175 // Append menus to the menubar
176 m_menuBar = new wxMenuBar();
177 m_menuBar->Append(m_menuFile, _("&File"));
178 SetMenuBar(m_menuBar);
179
180 #if wxUSE_STATUSBAR
181 // Status bar
182 CreateStatusBar(2);
183 #endif // wxUSE_STATUSBAR
184
185 // Make a textctrl for logging
186 m_text = new wxTextCtrl(this, wxID_ANY,
187 _("Welcome to wxSocket demo: Server\n"),
188 wxDefaultPosition, wxDefaultSize,
189 wxTE_MULTILINE | wxTE_READONLY);
190 delete wxLog::SetActiveTarget(new wxLogTextCtrl(m_text));
191
192 // Create the address - defaults to localhost:0 initially
193 #if wxUSE_IPV6
194 wxIPV6address addr;
195 #else
196 wxIPV4address addr;
197 #endif
198 addr.Service(3000);
199
200 // Create the socket
201 m_server = new wxSocketServer(addr);
202
203 // We use Ok() here to see if the server is really listening
204 if (! m_server->Ok())
205 {
206 wxLogMessage("Could not listen at the specified port !");
207 return;
208 }
209 else
210 {
211 wxLogMessage("Server listening.");
212 }
213
214 // Setup the event handler and subscribe to connection events
215 m_server->SetEventHandler(*this, SERVER_ID);
216 m_server->SetNotify(wxSOCKET_CONNECTION_FLAG);
217 m_server->Notify(true);
218
219 m_busy = false;
220 m_numClients = 0;
221 UpdateStatusBar();
222 }
223
224 MyFrame::~MyFrame()
225 {
226 // No delayed deletion here, as the frame is dying anyway
227 delete m_server;
228 }
229
230 // event handlers
231
232 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
233 {
234 // true is to force the frame to close
235 Close(true);
236 }
237
238 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
239 {
240 wxMessageBox(_("wxSocket demo: Server\n(c) 1999 Guillermo Rodriguez Garcia\n"),
241 _("About Server"),
242 wxOK | wxICON_INFORMATION, this);
243 }
244
245 void MyFrame::Test1(wxSocketBase *sock)
246 {
247 TestLogger logtest("Test 1");
248
249 // Receive data from socket and send it back. We will first
250 // get a byte with the buffer size, so we can specify the
251 // exact size and use the wxSOCKET_WAITALL flag. Also, we
252 // disabled input events so we won't have unwanted reentrance.
253 // This way we can avoid the infamous wxSOCKET_BLOCK flag.
254
255 sock->SetFlags(wxSOCKET_WAITALL);
256
257 // Read the size
258 unsigned char len;
259 sock->Read(&len, 1);
260 wxCharBuffer buf(len);
261
262 // Read the data
263 sock->Read(buf.data(), len);
264 wxLogMessage("Got the data, sending it back");
265
266 // Write it back
267 sock->Write(buf, len);
268 }
269
270 void MyFrame::Test2(wxSocketBase *sock)
271 {
272 char buf[4096];
273
274 TestLogger logtest("Test 2");
275
276 // We don't need to set flags because ReadMsg and WriteMsg
277 // are not affected by them anyway.
278
279 // Read the message
280 wxUint32 len = sock->ReadMsg(buf, sizeof(buf)).LastCount();
281 if ( !len )
282 {
283 wxLogError("Failed to read message.");
284 return;
285 }
286
287 wxLogMessage("Got \"%s\" from client.", wxString::FromUTF8(buf, len));
288 wxLogMessage("Sending the data back");
289
290 // Write it back
291 sock->WriteMsg(buf, len);
292 }
293
294 void MyFrame::Test3(wxSocketBase *sock)
295 {
296 TestLogger logtest("Test 3");
297
298 // This test is similar to the first one, but the len is
299 // expressed in kbytes - this tests large data transfers.
300
301 sock->SetFlags(wxSOCKET_WAITALL);
302
303 // Read the size
304 unsigned char len;
305 sock->Read(&len, 1);
306 wxCharBuffer buf(len*1024);
307
308 // Read the data
309 sock->Read(buf.data(), len * 1024);
310 wxLogMessage("Got the data, sending it back");
311
312 // Write it back
313 sock->Write(buf, len * 1024);
314 }
315
316 void MyFrame::OnServerEvent(wxSocketEvent& event)
317 {
318 wxString s = _("OnServerEvent: ");
319 wxSocketBase *sock;
320
321 switch(event.GetSocketEvent())
322 {
323 case wxSOCKET_CONNECTION : s.Append(_("wxSOCKET_CONNECTION\n")); break;
324 default : s.Append(_("Unexpected event !\n")); break;
325 }
326
327 m_text->AppendText(s);
328
329 // Accept new connection if there is one in the pending
330 // connections queue, else exit. We use Accept(false) for
331 // non-blocking accept (although if we got here, there
332 // should ALWAYS be a pending connection).
333
334 sock = m_server->Accept(false);
335
336 if (sock)
337 {
338 wxLogMessage("New client connection accepted");
339 }
340 else
341 {
342 wxLogMessage("Error: couldn't accept a new connection");
343 return;
344 }
345
346 sock->SetEventHandler(*this, SOCKET_ID);
347 sock->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
348 sock->Notify(true);
349
350 m_numClients++;
351 UpdateStatusBar();
352 }
353
354 void MyFrame::OnSocketEvent(wxSocketEvent& event)
355 {
356 wxString s = _("OnSocketEvent: ");
357 wxSocketBase *sock = event.GetSocket();
358
359 // First, print a message
360 switch(event.GetSocketEvent())
361 {
362 case wxSOCKET_INPUT : s.Append(_("wxSOCKET_INPUT\n")); break;
363 case wxSOCKET_LOST : s.Append(_("wxSOCKET_LOST\n")); break;
364 default : s.Append(_("Unexpected event !\n")); break;
365 }
366
367 m_text->AppendText(s);
368
369 // Now we process the event
370 switch(event.GetSocketEvent())
371 {
372 case wxSOCKET_INPUT:
373 {
374 // We disable input events, so that the test doesn't trigger
375 // wxSocketEvent again.
376 sock->SetNotify(wxSOCKET_LOST_FLAG);
377
378 // Which test are we going to run?
379 unsigned char c;
380 sock->Read(&c, 1);
381
382 switch (c)
383 {
384 case 0xBE: Test1(sock); break;
385 case 0xCE: Test2(sock); break;
386 case 0xDE: Test3(sock); break;
387 default:
388 wxLogMessage("Unknown test id received from client");
389 }
390
391 // Enable input events again.
392 sock->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG);
393 break;
394 }
395 case wxSOCKET_LOST:
396 {
397 m_numClients--;
398
399 // Destroy() should be used instead of delete wherever possible,
400 // due to the fact that wxSocket uses 'delayed events' (see the
401 // documentation for wxPostEvent) and we don't want an event to
402 // arrive to the event handler (the frame, here) after the socket
403 // has been deleted. Also, we might be doing some other thing with
404 // the socket at the same time; for example, we might be in the
405 // middle of a test or something. Destroy() takes care of all
406 // this for us.
407
408 wxLogMessage("Deleting socket.");
409 sock->Destroy();
410 break;
411 }
412 default: ;
413 }
414
415 UpdateStatusBar();
416 }
417
418 // convenience functions
419
420 void MyFrame::UpdateStatusBar()
421 {
422 #if wxUSE_STATUSBAR
423 wxString s;
424 s.Printf(_("%d clients connected"), m_numClients);
425 SetStatusText(s, 1);
426 #endif // wxUSE_STATUSBAR
427 }