]> git.saurik.com Git - wxWidgets.git/blob - samples/sockets/server.cpp
548ad955b699eec263e9a1831734d5534f8e2f35
[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 #if defined(__GNUG__) && !defined(__APPLE__)
21 #pragma implementation
22 #pragma interface
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(__WXX11__) || defined(__WXMOTIF__) || defined(__WXMAC__)
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 wxWidgets 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 = wxID_EXIT,
100 SERVER_ABOUT = wxID_ABOUT,
101
102 // id for sockets
103 SERVER_ID = 100,
104 SOCKET_ID
105 };
106
107 // --------------------------------------------------------------------------
108 // event tables and other macros for wxWidgets
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, wxID_ANY,
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 #if wxUSE_STATUSBAR
167 // Status bar
168 CreateStatusBar(2);
169 #endif // wxUSE_STATUSBAR
170
171 // Make a textctrl for logging
172 m_text = new wxTextCtrl(this, wxID_ANY,
173 _("Welcome to wxSocket demo: Server\n"),
174 wxDefaultPosition, wxDefaultSize,
175 wxTE_MULTILINE | wxTE_READONLY);
176
177 // Create the address - defaults to localhost:0 initially
178 wxIPV4address addr;
179 addr.Service(3000);
180
181 // Create the socket
182 m_server = new wxSocketServer(addr);
183
184 // We use Ok() here to see if the server is really listening
185 if (! m_server->Ok())
186 {
187 m_text->AppendText(_("Could not listen at the specified port !\n\n"));
188 return;
189 }
190 else
191 {
192 m_text->AppendText(_("Server listening.\n\n"));
193 }
194
195 // Setup the event handler and subscribe to connection events
196 m_server->SetEventHandler(*this, SERVER_ID);
197 m_server->SetNotify(wxSOCKET_CONNECTION_FLAG);
198 m_server->Notify(true);
199
200 m_busy = false;
201 m_numClients = 0;
202 UpdateStatusBar();
203 }
204
205 MyFrame::~MyFrame()
206 {
207 // No delayed deletion here, as the frame is dying anyway
208 delete m_server;
209 }
210
211 // event handlers
212
213 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
214 {
215 // true is to force the frame to close
216 Close(true);
217 }
218
219 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
220 {
221 wxMessageBox(_("wxSocket demo: Server\n(c) 1999 Guillermo Rodriguez Garcia\n"),
222 _("About Server"),
223 wxOK | wxICON_INFORMATION, this);
224 }
225
226 void MyFrame::Test1(wxSocketBase *sock)
227 {
228 unsigned char len;
229 char *buf;
230
231 m_text->AppendText(_("Test 1 begins\n"));
232
233 // Receive data from socket and send it back. We will first
234 // get a byte with the buffer size, so we can specify the
235 // exact size and use the wxSOCKET_WAITALL flag. Also, we
236 // disabled input events so we won't have unwanted reentrance.
237 // This way we can avoid the infamous wxSOCKET_BLOCK flag.
238
239 sock->SetFlags(wxSOCKET_WAITALL);
240
241 // Read the size
242 sock->Read(&len, 1);
243 buf = new char[len];
244
245 // Read the data
246 sock->Read(buf, len);
247 m_text->AppendText(_("Got the data, sending it back\n"));
248
249 // Write it back
250 sock->Write(buf, len);
251 delete[] buf;
252
253 m_text->AppendText(_("Test 1 ends\n\n"));
254 }
255
256 void MyFrame::Test2(wxSocketBase *sock)
257 {
258 #define MAX_MSG_SIZE 10000
259
260 wxString s;
261 wxChar *buf = new wxChar[MAX_MSG_SIZE];
262 wxUint32 len;
263
264 m_text->AppendText(_("Test 2 begins\n"));
265
266 // We don't need to set flags because ReadMsg and WriteMsg
267 // are not affected by them anyway.
268
269 // Read the message
270 len = sock->ReadMsg(buf, MAX_MSG_SIZE * sizeof(wxChar)).LastCount();
271 s.Printf(_("Client says: %s\n"), buf);
272 m_text->AppendText(s);
273 m_text->AppendText(_("Sending the data back\n"));
274
275 // Write it back
276 sock->WriteMsg(buf, len);
277 delete[] buf;
278
279 m_text->AppendText(_("Test 2 ends\n\n"));
280
281 #undef MAX_MSG_SIZE
282 }
283
284 void MyFrame::Test3(wxSocketBase *sock)
285 {
286 unsigned char len;
287 char *buf;
288
289 m_text->AppendText(_("Test 3 begins\n"));
290
291 // This test is similar to the first one, but the len is
292 // expressed in kbytes - this tests large data transfers.
293
294 sock->SetFlags(wxSOCKET_WAITALL);
295
296 // Read the size
297 sock->Read(&len, 1);
298 buf = new char[len * 1024];
299
300 // Read the data
301 sock->Read(buf, len * 1024);
302 m_text->AppendText(_("Got the data, sending it back\n"));
303
304 // Write it back
305 sock->Write(buf, len * 1024);
306 delete[] buf;
307
308 m_text->AppendText(_("Test 3 ends\n\n"));
309 }
310
311 void MyFrame::OnServerEvent(wxSocketEvent& event)
312 {
313 wxString s = _("OnServerEvent: ");
314 wxSocketBase *sock;
315
316 switch(event.GetSocketEvent())
317 {
318 case wxSOCKET_CONNECTION : s.Append(_("wxSOCKET_CONNECTION\n")); break;
319 default : s.Append(_("Unexpected event !\n")); break;
320 }
321
322 m_text->AppendText(s);
323
324 // Accept new connection if there is one in the pending
325 // connections queue, else exit. We use Accept(false) for
326 // non-blocking accept (although if we got here, there
327 // should ALWAYS be a pending connection).
328
329 sock = m_server->Accept(false);
330
331 if (sock)
332 {
333 m_text->AppendText(_("New client connection accepted\n\n"));
334 }
335 else
336 {
337 m_text->AppendText(_("Error: couldn't accept a new connection\n\n"));
338 return;
339 }
340
341 sock->SetEventHandler(*this, SOCKET_ID);
342 sock->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
343 sock->Notify(true);
344
345 m_numClients++;
346 UpdateStatusBar();
347 }
348
349 void MyFrame::OnSocketEvent(wxSocketEvent& event)
350 {
351 wxString s = _("OnSocketEvent: ");
352 wxSocketBase *sock = event.GetSocket();
353
354 // First, print a message
355 switch(event.GetSocketEvent())
356 {
357 case wxSOCKET_INPUT : s.Append(_("wxSOCKET_INPUT\n")); break;
358 case wxSOCKET_LOST : s.Append(_("wxSOCKET_LOST\n")); break;
359 default : s.Append(_("Unexpected event !\n")); break;
360 }
361
362 m_text->AppendText(s);
363
364 // Now we process the event
365 switch(event.GetSocketEvent())
366 {
367 case wxSOCKET_INPUT:
368 {
369 // We disable input events, so that the test doesn't trigger
370 // wxSocketEvent again.
371 sock->SetNotify(wxSOCKET_LOST_FLAG);
372
373 // Which test are we going to run?
374 unsigned char c;
375 sock->Read(&c, 1);
376
377 switch (c)
378 {
379 case 0xBE: Test1(sock); break;
380 case 0xCE: Test2(sock); break;
381 case 0xDE: Test3(sock); break;
382 default:
383 m_text->AppendText(_("Unknown test id received from client\n\n"));
384 }
385
386 // Enable input events again.
387 sock->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG);
388 break;
389 }
390 case wxSOCKET_LOST:
391 {
392 m_numClients--;
393
394 // Destroy() should be used instead of delete wherever possible,
395 // due to the fact that wxSocket uses 'delayed events' (see the
396 // documentation for wxPostEvent) and we don't want an event to
397 // arrive to the event handler (the frame, here) after the socket
398 // has been deleted. Also, we might be doing some other thing with
399 // the socket at the same time; for example, we might be in the
400 // middle of a test or something. Destroy() takes care of all
401 // this for us.
402
403 m_text->AppendText(_("Deleting socket.\n\n"));
404 sock->Destroy();
405 break;
406 }
407 default: ;
408 }
409
410 UpdateStatusBar();
411 }
412
413 // convenience functions
414
415 void MyFrame::UpdateStatusBar()
416 {
417 #if wxUSE_STATUSBAR
418 wxString s;
419 s.Printf(_("%d clients connected"), m_numClients);
420 SetStatusText(s, 1);
421 #endif // wxUSE_STATUSBAR
422 }