]>
git.saurik.com Git - wxWidgets.git/blob - samples/sockets/server.cpp
1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Server for wxSocket demo
4 // Author: Guillermo Rodriguez Garcia <guille@iies.es>
8 // Copyright: (c) 1999 Guillermo Rodriguez Garcia
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ==========================================================================
14 // ==========================================================================
16 // --------------------------------------------------------------------------
18 // --------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx/wx.h".
21 #include "wx/wxprec.h"
27 // for all others, include the necessary headers
32 #include "wx/socket.h"
34 // --------------------------------------------------------------------------
36 // --------------------------------------------------------------------------
38 // the application icon
39 #include "mondrian.xpm"
41 // --------------------------------------------------------------------------
43 // --------------------------------------------------------------------------
45 // Define a new application type
46 class MyApp
: public wxApp
49 virtual bool OnInit();
52 // Define a new frame type: this is going to be our main frame
53 class MyFrame
: public wxFrame
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
);
65 void Test1(wxSocketBase
*sock
);
66 void Test2(wxSocketBase
*sock
);
67 void Test3(wxSocketBase
*sock
);
69 // convenience functions
70 void UpdateStatusBar();
73 wxSocketServer
*m_server
;
80 // any class wishing to process wxWidgets events must use this macro
84 // simple helper class to log start and end of each test
88 TestLogger(const wxString
& name
) : m_name(name
)
90 wxLogMessage("=== %s begins ===", m_name
);
95 wxLogMessage("=== %s ends ===", m_name
);
99 const wxString m_name
;
102 // --------------------------------------------------------------------------
104 // --------------------------------------------------------------------------
106 // IDs for the controls and the menu commands
110 SERVER_QUIT
= wxID_EXIT
,
111 SERVER_ABOUT
= wxID_ABOUT
,
118 // --------------------------------------------------------------------------
119 // event tables and other macros for wxWidgets
120 // --------------------------------------------------------------------------
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
)
132 // ==========================================================================
134 // ==========================================================================
136 // --------------------------------------------------------------------------
137 // the application class
138 // --------------------------------------------------------------------------
142 if ( !wxApp::OnInit() )
145 // Create the main application window
146 MyFrame
*frame
= new MyFrame();
148 // Show it and tell the application that it's our main window
156 // --------------------------------------------------------------------------
158 // --------------------------------------------------------------------------
162 MyFrame::MyFrame() : wxFrame((wxFrame
*)NULL
, wxID_ANY
,
163 _("wxSocket demo: Server"),
164 wxDefaultPosition
, wxSize(300, 200))
166 // Give the frame an icon
167 SetIcon(wxICON(mondrian
));
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"));
175 // Append menus to the menubar
176 m_menuBar
= new wxMenuBar();
177 m_menuBar
->Append(m_menuFile
, _("&File"));
178 SetMenuBar(m_menuBar
);
183 #endif // wxUSE_STATUSBAR
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
));
192 // Create the address - defaults to localhost:0 initially
201 m_server
= new wxSocketServer(addr
);
203 // We use Ok() here to see if the server is really listening
204 if (! m_server
->Ok())
206 wxLogMessage("Could not listen at the specified port !");
211 wxLogMessage("Server listening.");
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);
226 // No delayed deletion here, as the frame is dying anyway
232 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
234 // true is to force the frame to close
238 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
240 wxMessageBox(_("wxSocket demo: Server\n(c) 1999 Guillermo Rodriguez Garcia\n"),
242 wxOK
| wxICON_INFORMATION
, this);
245 void MyFrame::Test1(wxSocketBase
*sock
)
247 TestLogger
logtest("Test 1");
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.
255 sock
->SetFlags(wxSOCKET_WAITALL
);
260 wxCharBuffer
buf(len
);
263 sock
->Read(buf
.data(), len
);
264 wxLogMessage("Got the data, sending it back");
267 sock
->Write(buf
, len
);
270 void MyFrame::Test2(wxSocketBase
*sock
)
274 TestLogger
logtest("Test 2");
276 // We don't need to set flags because ReadMsg and WriteMsg
277 // are not affected by them anyway.
280 wxUint32 len
= sock
->ReadMsg(buf
, sizeof(buf
)).LastCount();
283 wxLogError("Failed to read message.");
287 wxLogMessage("Got \"%s\" from client.", wxString::FromUTF8(buf
, len
));
288 wxLogMessage("Sending the data back");
291 sock
->WriteMsg(buf
, len
);
294 void MyFrame::Test3(wxSocketBase
*sock
)
296 TestLogger
logtest("Test 3");
298 // This test is similar to the first one, but the len is
299 // expressed in kbytes - this tests large data transfers.
301 sock
->SetFlags(wxSOCKET_WAITALL
);
306 wxCharBuffer
buf(len
*1024);
309 sock
->Read(buf
.data(), len
* 1024);
310 wxLogMessage("Got the data, sending it back");
313 sock
->Write(buf
, len
* 1024);
316 void MyFrame::OnServerEvent(wxSocketEvent
& event
)
318 wxString s
= _("OnServerEvent: ");
321 switch(event
.GetSocketEvent())
323 case wxSOCKET_CONNECTION
: s
.Append(_("wxSOCKET_CONNECTION\n")); break;
324 default : s
.Append(_("Unexpected event !\n")); break;
327 m_text
->AppendText(s
);
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).
334 sock
= m_server
->Accept(false);
338 wxLogMessage("New client connection accepted");
342 wxLogMessage("Error: couldn't accept a new connection");
346 sock
->SetEventHandler(*this, SOCKET_ID
);
347 sock
->SetNotify(wxSOCKET_INPUT_FLAG
| wxSOCKET_LOST_FLAG
);
354 void MyFrame::OnSocketEvent(wxSocketEvent
& event
)
356 wxString s
= _("OnSocketEvent: ");
357 wxSocketBase
*sock
= event
.GetSocket();
359 // First, print a message
360 switch(event
.GetSocketEvent())
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;
367 m_text
->AppendText(s
);
369 // Now we process the event
370 switch(event
.GetSocketEvent())
374 // We disable input events, so that the test doesn't trigger
375 // wxSocketEvent again.
376 sock
->SetNotify(wxSOCKET_LOST_FLAG
);
378 // Which test are we going to run?
384 case 0xBE: Test1(sock
); break;
385 case 0xCE: Test2(sock
); break;
386 case 0xDE: Test3(sock
); break;
388 wxLogMessage("Unknown test id received from client");
391 // Enable input events again.
392 sock
->SetNotify(wxSOCKET_LOST_FLAG
| wxSOCKET_INPUT_FLAG
);
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
408 wxLogMessage("Deleting socket.");
418 // convenience functions
420 void MyFrame::UpdateStatusBar()
424 s
.Printf(_("%d clients connected"), m_numClients
);
426 #endif // wxUSE_STATUSBAR