]> git.saurik.com Git - wxWidgets.git/blob - samples/wxsocket/server.cpp
Forgot one.
[wxWidgets.git] / samples / wxsocket / 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 wxPanel *m_panel;
82 wxTextCtrl *m_text;
83 wxMenu *m_menuFile;
84 wxMenuBar *m_menuBar;
85 bool m_busy;
86 int m_numClients;
87
88 // any class wishing to process wxWindows events must use this macro
89 DECLARE_EVENT_TABLE()
90 };
91
92 // --------------------------------------------------------------------------
93 // constants
94 // --------------------------------------------------------------------------
95
96 // IDs for the controls and the menu commands
97 enum
98 {
99 // menu items
100 SERVER_QUIT = 1000,
101 SERVER_ABOUT,
102
103 // id for sockets
104 SERVER_ID,
105 SOCKET_ID
106 };
107
108 // --------------------------------------------------------------------------
109 // event tables and other macros for wxWindows
110 // --------------------------------------------------------------------------
111
112 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
113 EVT_MENU(SERVER_QUIT, MyFrame::OnQuit)
114 EVT_MENU(SERVER_ABOUT, MyFrame::OnAbout)
115 EVT_SOCKET(SERVER_ID, MyFrame::OnServerEvent)
116 EVT_SOCKET(SOCKET_ID, MyFrame::OnSocketEvent)
117 END_EVENT_TABLE()
118
119 IMPLEMENT_APP(MyApp)
120
121
122 // To append sockets for delayed deletion
123 extern wxList wxPendingDelete;
124
125
126 // ==========================================================================
127 // implementation
128 // ==========================================================================
129
130 // --------------------------------------------------------------------------
131 // the application class
132 // --------------------------------------------------------------------------
133
134 bool MyApp::OnInit()
135 {
136 // Create the main application window
137 MyFrame *frame = new MyFrame();
138
139 // Show it and tell the application that it's our main window
140 frame->Show(TRUE);
141 SetTopWindow(frame);
142
143 // success
144 return TRUE;
145 }
146
147 // --------------------------------------------------------------------------
148 // main frame
149 // --------------------------------------------------------------------------
150
151 // frame constructor
152 MyFrame::MyFrame() : wxFrame((wxFrame *)NULL, -1,
153 _T("wxSocket demo: Server"),
154 wxDefaultPosition, wxSize(300, 200))
155 {
156 // Give the frame an icon
157 SetIcon(wxICON(mondrian));
158
159 // Make menus
160 m_menuFile = new wxMenu();
161 m_menuFile->Append(SERVER_ABOUT, _T("&About...\tCtrl-A"), _T("Show about dialog"));
162 m_menuFile->AppendSeparator();
163 m_menuFile->Append(SERVER_QUIT, _T("E&xit\tAlt-X"), _T("Quit server"));
164
165 // Append menus to the menubar
166 m_menuBar = new wxMenuBar();
167 m_menuBar->Append(m_menuFile, _T("&File"));
168 SetMenuBar(m_menuBar);
169
170 // Status bar
171 CreateStatusBar(2);
172
173 // Make a panel with a textctrl in it
174 m_panel = new wxPanel(this, -1, wxPoint(0, 0), GetClientSize());
175 m_text = new wxTextCtrl(m_panel, -1,
176 _T("Welcome to wxSocket demo: Server\n"),
177 wxPoint(0, 0), m_panel->GetClientSize(),
178 wxTE_MULTILINE | wxTE_READONLY);
179
180 // Create the socket
181 wxIPV4address addr;
182 addr.Service(3000);
183
184 m_server = new wxSocketServer(addr);
185 m_server->SetEventHandler(*this, SERVER_ID);
186 m_server->SetNotify(wxSOCKET_CONNECTION_FLAG);
187 m_server->Notify(TRUE);
188
189 // We use Ok() here to see if the server is really listening
190 if (m_server->Ok())
191 m_text->AppendText(_T("Server listening.\n\n"));
192 else
193 m_text->AppendText(_T("Could not listen at the specified port !\n\n"));
194
195 m_busy = FALSE;
196 m_numClients = 0;
197 UpdateStatusBar();
198 }
199
200 MyFrame::~MyFrame()
201 {
202 delete m_server;
203 }
204
205 // event handlers
206
207 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
208 {
209 // TRUE is to force the frame to close
210 Close(TRUE);
211 }
212
213 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
214 {
215 wxMessageBox(_T("wxSocket demo: Server\n")
216 _T("(c) 1999 Guillermo Rodriguez Garcia\n"),
217 _T("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(_T("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 WAITALL flag. Also, we disabled
231 // input events so we won't have unwanted reentrance. This
232 // way we can avoid the infamous BLOCK (formerly SPEED) flag.
233 //
234 sock->SetFlags(wxSOCKET_WAITALL);
235
236 sock->Read((char *)&len, 1);
237
238 buf = (char *)malloc(len);
239 sock->Read(buf, len);
240 sock->Write(buf, len);
241 free(buf);
242
243 m_text->AppendText(_T("Test 1 ends\n"));
244 }
245
246 void MyFrame::Test2(wxSocketBase *sock)
247 {
248 #define MAX_MSG_SIZE 10000
249
250 wxString s;
251 char *buf = (char *)malloc(MAX_MSG_SIZE);
252 wxUint32 len;
253
254 m_text->AppendText(_T("Test 2 begins\n"));
255
256 // We don't need to set flags because ReadMsg and WriteMsg
257 // are not affected by them anyway.
258 //
259 len = sock->ReadMsg(buf, MAX_MSG_SIZE).LastCount();
260
261 s.Printf(_T("Client says: %s\n"), buf);
262 m_text->AppendText(s);
263
264 sock->WriteMsg(buf, len);
265 free(buf);
266
267 m_text->AppendText(_T("Test 2 ends\n"));
268
269 #undef MAX_MSG_SIZE
270 }
271
272 void MyFrame::Test3(wxSocketBase *sock)
273 {
274 m_text->AppendText(_T("Test 3 begins\n"));
275 m_text->AppendText(_T("(not implemented)\n"));
276 m_text->AppendText(_T("Test 3 ends\n"));
277 }
278
279 void MyFrame::OnServerEvent(wxSocketEvent& event)
280 {
281 wxString s = _T("OnServerEvent: ");
282 wxSocketBase *sock;
283
284 switch(event.SocketEvent())
285 {
286 case wxSOCKET_CONNECTION : s.Append(_T("wxSOCKET_CONNECTION\n")); break;
287 default : s.Append(_T("Unexpected event !\n")); break;
288 }
289
290 m_text->AppendText(s);
291
292 // Accept new connection if there is one in the pending
293 // connections queue, else exit. We use Accept(FALSE) for
294 // non-blocking accept (although if we got here, there
295 // should ALWAYS be a pending connection).
296 //
297 sock = m_server->Accept(FALSE);
298
299 if (sock)
300 {
301 m_text->AppendText(_T("New client connection accepted\n"));
302 }
303 else
304 {
305 m_text->AppendText(_T("Error: couldn't accept a new connection"));
306 return;
307 }
308
309 sock->SetEventHandler(*this, SOCKET_ID);
310 sock->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
311 sock->Notify(TRUE);
312
313 m_numClients++;
314 UpdateStatusBar();
315 }
316
317 void MyFrame::OnSocketEvent(wxSocketEvent& event)
318 {
319 wxSocketBase *sock = event.Socket();
320 wxString s = _T("OnSocketEvent: ");
321
322 // We first print a msg
323 switch(event.SocketEvent())
324 {
325 case wxSOCKET_INPUT: s.Append(_T("wxSOCKET_INPUT\n")); break;
326 case wxSOCKET_LOST: s.Append(_T("wxSOCKET_LOST\n")); break;
327 default: s.Append(_T("unexpected event !\n"));
328 }
329
330 m_text->AppendText(s);
331
332 // Now we process the event
333 switch(event.SocketEvent())
334 {
335 case wxSOCKET_INPUT:
336 {
337 // We disable input events, so that the test doesn't trigger
338 // wxSocketEvent again.
339 sock->SetNotify(wxSOCKET_LOST_FLAG);
340
341 // Which test are we going to run?
342 unsigned char c;
343 sock->Read((char *)&c ,1);
344
345 switch (c)
346 {
347 case 0xBE: Test1(sock); break;
348 case 0xCE: Test2(sock); break;
349 case 0xDE: Test3(sock); break;
350 default: s.Append(_T("Unknown test id received from client\n"));
351 }
352
353 // Enable input events again.
354 sock->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG);
355 break;
356 }
357 case wxSOCKET_LOST:
358 {
359 m_numClients--;
360
361 // We cannot delete the socket right now because we can
362 // be in the middle of a test or something. So we append
363 // it to the list of objects to be deleted.
364 m_text->AppendText(_T("Deleting socket.\n"));
365 wxPendingDelete.Append(sock);
366 break;
367 }
368 default: ;
369 }
370
371 UpdateStatusBar();
372 }
373
374 // convenience functions
375
376 void MyFrame::UpdateStatusBar()
377 {
378 wxString s;
379 s.Printf(_T("%d clients connected"), m_numClients);
380 SetStatusText(s, 1);
381 }