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