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