]>
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 // this example is currently written to use only IP or only IPv6 sockets, it
35 // should be extended to allow using either in the future
37 typedef wxIPV6address IPaddress
;
39 typedef wxIPV4address IPaddress
;
42 // --------------------------------------------------------------------------
44 // --------------------------------------------------------------------------
46 // the application icon
47 #include "mondrian.xpm"
49 // --------------------------------------------------------------------------
51 // --------------------------------------------------------------------------
53 // Define a new application type
54 class MyApp
: public wxApp
57 virtual bool OnInit();
60 // Define a new frame type: this is going to be our main frame
61 class MyFrame
: public wxFrame
67 // event handlers (these functions should _not_ be virtual)
68 void OnUDPTest(wxCommandEvent
& event
);
69 void OnQuit(wxCommandEvent
& event
);
70 void OnAbout(wxCommandEvent
& event
);
71 void OnServerEvent(wxSocketEvent
& event
);
72 void OnSocketEvent(wxSocketEvent
& event
);
74 void Test1(wxSocketBase
*sock
);
75 void Test2(wxSocketBase
*sock
);
76 void Test3(wxSocketBase
*sock
);
78 // convenience functions
79 void UpdateStatusBar();
82 wxSocketServer
*m_server
;
89 // any class wishing to process wxWidgets events must use this macro
93 // simple helper class to log start and end of each test
97 TestLogger(const wxString
& name
) : m_name(name
)
99 wxLogMessage("=== %s begins ===", m_name
);
104 wxLogMessage("=== %s ends ===", m_name
);
108 const wxString m_name
;
111 // --------------------------------------------------------------------------
113 // --------------------------------------------------------------------------
115 // IDs for the controls and the menu commands
120 SERVER_QUIT
= wxID_EXIT
,
121 SERVER_ABOUT
= wxID_ABOUT
,
128 // --------------------------------------------------------------------------
129 // event tables and other macros for wxWidgets
130 // --------------------------------------------------------------------------
132 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
133 EVT_MENU(SERVER_QUIT
, MyFrame::OnQuit
)
134 EVT_MENU(SERVER_ABOUT
, MyFrame::OnAbout
)
135 EVT_MENU(SERVER_UDPTEST
, MyFrame::OnUDPTest
)
136 EVT_SOCKET(SERVER_ID
, MyFrame::OnServerEvent
)
137 EVT_SOCKET(SOCKET_ID
, MyFrame::OnSocketEvent
)
143 // ==========================================================================
145 // ==========================================================================
147 // --------------------------------------------------------------------------
148 // the application class
149 // --------------------------------------------------------------------------
153 if ( !wxApp::OnInit() )
156 // Create the main application window
157 MyFrame
*frame
= new MyFrame();
159 // Show it and tell the application that it's our main window
167 // --------------------------------------------------------------------------
169 // --------------------------------------------------------------------------
173 MyFrame::MyFrame() : wxFrame((wxFrame
*)NULL
, wxID_ANY
,
174 _("wxSocket demo: Server"),
175 wxDefaultPosition
, wxSize(300, 200))
177 // Give the frame an icon
178 SetIcon(wxICON(mondrian
));
181 m_menuFile
= new wxMenu();
182 m_menuFile
->Append(SERVER_UDPTEST
, "&UDP test\tCtrl-U");
183 m_menuFile
->AppendSeparator();
184 m_menuFile
->Append(SERVER_ABOUT
, _("&About...\tCtrl-A"), _("Show about dialog"));
185 m_menuFile
->AppendSeparator();
186 m_menuFile
->Append(SERVER_QUIT
, _("E&xit\tAlt-X"), _("Quit server"));
188 // Append menus to the menubar
189 m_menuBar
= new wxMenuBar();
190 m_menuBar
->Append(m_menuFile
, _("&File"));
191 SetMenuBar(m_menuBar
);
196 #endif // wxUSE_STATUSBAR
198 // Make a textctrl for logging
199 m_text
= new wxTextCtrl(this, wxID_ANY
,
200 _("Welcome to wxSocket demo: Server\n"),
201 wxDefaultPosition
, wxDefaultSize
,
202 wxTE_MULTILINE
| wxTE_READONLY
);
203 delete wxLog::SetActiveTarget(new wxLogTextCtrl(m_text
));
205 // Create the address - defaults to localhost:0 initially
209 wxLogMessage("Creating server at %s:%u", addr
.IPAddress(), addr
.Service());
212 m_server
= new wxSocketServer(addr
);
214 // We use Ok() here to see if the server is really listening
215 if (! m_server
->Ok())
217 wxLogMessage("Could not listen at the specified port !");
222 if ( !m_server
->GetLocal(addrReal
) )
224 wxLogMessage("ERROR: couldn't get the address we bound to");
228 wxLogMessage("Server listening at %s:%u",
229 addrReal
.IPAddress(), addrReal
.Service());
232 // Setup the event handler and subscribe to connection events
233 m_server
->SetEventHandler(*this, SERVER_ID
);
234 m_server
->SetNotify(wxSOCKET_CONNECTION_FLAG
);
235 m_server
->Notify(true);
244 // No delayed deletion here, as the frame is dying anyway
250 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
252 // true is to force the frame to close
256 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
258 wxMessageBox(_("wxSocket demo: Server\n(c) 1999 Guillermo Rodriguez Garcia\n"),
260 wxOK
| wxICON_INFORMATION
, this);
263 void MyFrame::OnUDPTest(wxCommandEvent
& WXUNUSED(event
))
265 TestLogger
logtest("UDP test");
269 wxDatagramSocket
sock(addr
);
272 size_t n
= sock
.RecvFrom(addr
, buf
, sizeof(buf
)).LastCount();
275 wxLogMessage("ERROR: failed to receive data");
279 wxLogMessage("Received \"%s\" from %s:%u.",
280 wxString::From8BitData(buf
, n
),
281 addr
.IPAddress(), addr
.Service());
283 for ( size_t i
= 0; i
< n
; i
++ )
286 if ( (c
>= 'A' && c
<= 'M') || (c
>= 'a' && c
<= 'm') )
288 else if ( (c
>= 'N' && c
<= 'Z') || (c
>= 'n' && c
<= 'z') )
292 if ( sock
.SendTo(addr
, buf
, n
).LastCount() != n
)
294 wxLogMessage("ERROR: failed to send data");
299 void MyFrame::Test1(wxSocketBase
*sock
)
301 TestLogger
logtest("Test 1");
303 // Receive data from socket and send it back. We will first
304 // get a byte with the buffer size, so we can specify the
305 // exact size and use the wxSOCKET_WAITALL flag. Also, we
306 // disabled input events so we won't have unwanted reentrance.
307 // This way we can avoid the infamous wxSOCKET_BLOCK flag.
309 sock
->SetFlags(wxSOCKET_WAITALL
);
314 wxCharBuffer
buf(len
);
317 sock
->Read(buf
.data(), len
);
318 wxLogMessage("Got the data, sending it back");
321 sock
->Write(buf
, len
);
324 void MyFrame::Test2(wxSocketBase
*sock
)
328 TestLogger
logtest("Test 2");
330 // We don't need to set flags because ReadMsg and WriteMsg
331 // are not affected by them anyway.
334 wxUint32 len
= sock
->ReadMsg(buf
, sizeof(buf
)).LastCount();
337 wxLogError("Failed to read message.");
341 wxLogMessage("Got \"%s\" from client.", wxString::FromUTF8(buf
, len
));
342 wxLogMessage("Sending the data back");
345 sock
->WriteMsg(buf
, len
);
348 void MyFrame::Test3(wxSocketBase
*sock
)
350 TestLogger
logtest("Test 3");
352 // This test is similar to the first one, but the len is
353 // expressed in kbytes - this tests large data transfers.
355 sock
->SetFlags(wxSOCKET_WAITALL
);
360 wxCharBuffer
buf(len
*1024);
363 sock
->Read(buf
.data(), len
* 1024);
364 wxLogMessage("Got the data, sending it back");
367 sock
->Write(buf
, len
* 1024);
370 void MyFrame::OnServerEvent(wxSocketEvent
& event
)
372 wxString s
= _("OnServerEvent: ");
375 switch(event
.GetSocketEvent())
377 case wxSOCKET_CONNECTION
: s
.Append(_("wxSOCKET_CONNECTION\n")); break;
378 default : s
.Append(_("Unexpected event !\n")); break;
381 m_text
->AppendText(s
);
383 // Accept new connection if there is one in the pending
384 // connections queue, else exit. We use Accept(false) for
385 // non-blocking accept (although if we got here, there
386 // should ALWAYS be a pending connection).
388 sock
= m_server
->Accept(false);
393 if ( !sock
->GetPeer(addr
) )
395 wxLogMessage("New connection from unknown client accepted.");
399 wxLogMessage("New client connection from %s:%u accepted",
400 addr
.IPAddress(), addr
.Service());
405 wxLogMessage("Error: couldn't accept a new connection");
409 sock
->SetEventHandler(*this, SOCKET_ID
);
410 sock
->SetNotify(wxSOCKET_INPUT_FLAG
| wxSOCKET_LOST_FLAG
);
417 void MyFrame::OnSocketEvent(wxSocketEvent
& event
)
419 wxString s
= _("OnSocketEvent: ");
420 wxSocketBase
*sock
= event
.GetSocket();
422 // First, print a message
423 switch(event
.GetSocketEvent())
425 case wxSOCKET_INPUT
: s
.Append(_("wxSOCKET_INPUT\n")); break;
426 case wxSOCKET_LOST
: s
.Append(_("wxSOCKET_LOST\n")); break;
427 default : s
.Append(_("Unexpected event !\n")); break;
430 m_text
->AppendText(s
);
432 // Now we process the event
433 switch(event
.GetSocketEvent())
437 // We disable input events, so that the test doesn't trigger
438 // wxSocketEvent again.
439 sock
->SetNotify(wxSOCKET_LOST_FLAG
);
441 // Which test are we going to run?
447 case 0xBE: Test1(sock
); break;
448 case 0xCE: Test2(sock
); break;
449 case 0xDE: Test3(sock
); break;
451 wxLogMessage("Unknown test id received from client");
454 // Enable input events again.
455 sock
->SetNotify(wxSOCKET_LOST_FLAG
| wxSOCKET_INPUT_FLAG
);
462 // Destroy() should be used instead of delete wherever possible,
463 // due to the fact that wxSocket uses 'delayed events' (see the
464 // documentation for wxPostEvent) and we don't want an event to
465 // arrive to the event handler (the frame, here) after the socket
466 // has been deleted. Also, we might be doing some other thing with
467 // the socket at the same time; for example, we might be in the
468 // middle of a test or something. Destroy() takes care of all
471 wxLogMessage("Deleting socket.");
481 // convenience functions
483 void MyFrame::UpdateStatusBar()
487 s
.Printf(_("%d clients connected"), m_numClients
);
489 #endif // wxUSE_STATUSBAR