]>
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>
7 // Copyright: (c) 1999 Guillermo Rodriguez Garcia
8 // (c) 2009 Vadim Zeitlin
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/busyinfo.h"
33 #include "wx/socket.h"
35 // this example is currently written to use only IP or only IPv6 sockets, it
36 // should be extended to allow using either in the future
38 typedef wxIPV6address IPaddress
;
40 typedef wxIPV4address IPaddress
;
43 // --------------------------------------------------------------------------
45 // --------------------------------------------------------------------------
47 // the application icon
48 #if !defined(__WXMSW__) && !defined(__WXPM__)
49 #include "../sample.xpm"
52 // --------------------------------------------------------------------------
54 // --------------------------------------------------------------------------
56 // Define a new application type
57 class MyApp
: public wxApp
60 virtual bool OnInit();
63 // Define a new frame type: this is going to be our main frame
64 class MyFrame
: public wxFrame
70 // event handlers (these functions should _not_ be virtual)
71 void OnUDPTest(wxCommandEvent
& event
);
72 void OnWaitForAccept(wxCommandEvent
& event
);
73 void OnQuit(wxCommandEvent
& event
);
74 void OnAbout(wxCommandEvent
& event
);
75 void OnServerEvent(wxSocketEvent
& event
);
76 void OnSocketEvent(wxSocketEvent
& event
);
78 void Test1(wxSocketBase
*sock
);
79 void Test2(wxSocketBase
*sock
);
80 void Test3(wxSocketBase
*sock
);
82 // convenience functions
83 void UpdateStatusBar();
86 wxSocketServer
*m_server
;
93 // any class wishing to process wxWidgets events must use this macro
97 // simple helper class to log start and end of each test
101 TestLogger(const wxString
& name
) : m_name(name
)
103 wxLogMessage("=== %s begins ===", m_name
);
108 wxLogMessage("=== %s ends ===", m_name
);
112 const wxString m_name
;
115 // --------------------------------------------------------------------------
117 // --------------------------------------------------------------------------
119 // IDs for the controls and the menu commands
124 SERVER_WAITFORACCEPT
,
125 SERVER_QUIT
= wxID_EXIT
,
126 SERVER_ABOUT
= wxID_ABOUT
,
133 // --------------------------------------------------------------------------
134 // event tables and other macros for wxWidgets
135 // --------------------------------------------------------------------------
137 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
138 EVT_MENU(SERVER_QUIT
, MyFrame::OnQuit
)
139 EVT_MENU(SERVER_ABOUT
, MyFrame::OnAbout
)
140 EVT_MENU(SERVER_UDPTEST
, MyFrame::OnUDPTest
)
141 EVT_MENU(SERVER_WAITFORACCEPT
, MyFrame::OnWaitForAccept
)
142 EVT_SOCKET(SERVER_ID
, MyFrame::OnServerEvent
)
143 EVT_SOCKET(SOCKET_ID
, MyFrame::OnSocketEvent
)
149 // ==========================================================================
151 // ==========================================================================
153 // --------------------------------------------------------------------------
154 // the application class
155 // --------------------------------------------------------------------------
159 if ( !wxApp::OnInit() )
162 // Create the main application window
163 MyFrame
*frame
= new MyFrame();
172 // --------------------------------------------------------------------------
174 // --------------------------------------------------------------------------
178 MyFrame::MyFrame() : wxFrame((wxFrame
*)NULL
, wxID_ANY
,
179 _("wxSocket demo: Server"),
180 wxDefaultPosition
, wxSize(300, 200))
182 // Give the frame an icon
183 SetIcon(wxICON(sample
));
186 m_menuFile
= new wxMenu();
187 m_menuFile
->Append(SERVER_WAITFORACCEPT
, "&Wait for connection\tCtrl-W");
188 m_menuFile
->Append(SERVER_UDPTEST
, "&UDP test\tCtrl-U");
189 m_menuFile
->AppendSeparator();
190 m_menuFile
->Append(SERVER_ABOUT
, _("&About...\tCtrl-A"), _("Show about dialog"));
191 m_menuFile
->AppendSeparator();
192 m_menuFile
->Append(SERVER_QUIT
, _("E&xit\tAlt-X"), _("Quit server"));
194 // Append menus to the menubar
195 m_menuBar
= new wxMenuBar();
196 m_menuBar
->Append(m_menuFile
, _("&File"));
197 SetMenuBar(m_menuBar
);
202 #endif // wxUSE_STATUSBAR
204 // Make a textctrl for logging
205 m_text
= new wxTextCtrl(this, wxID_ANY
,
206 _("Welcome to wxSocket demo: Server\n"),
207 wxDefaultPosition
, wxDefaultSize
,
208 wxTE_MULTILINE
| wxTE_READONLY
);
209 delete wxLog::SetActiveTarget(new wxLogTextCtrl(m_text
));
211 // Create the address - defaults to localhost:0 initially
215 wxLogMessage("Creating server at %s:%u", addr
.IPAddress(), addr
.Service());
218 m_server
= new wxSocketServer(addr
);
220 // We use IsOk() here to see if the server is really listening
221 if (! m_server
->IsOk())
223 wxLogMessage("Could not listen at the specified port !");
228 if ( !m_server
->GetLocal(addrReal
) )
230 wxLogMessage("ERROR: couldn't get the address we bound to");
234 wxLogMessage("Server listening at %s:%u",
235 addrReal
.IPAddress(), addrReal
.Service());
238 // Setup the event handler and subscribe to connection events
239 m_server
->SetEventHandler(*this, SERVER_ID
);
240 m_server
->SetNotify(wxSOCKET_CONNECTION_FLAG
);
241 m_server
->Notify(true);
250 // No delayed deletion here, as the frame is dying anyway
256 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
258 // true is to force the frame to close
262 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
264 wxMessageBox(_("wxSocket demo: Server\n(c) 1999 Guillermo Rodriguez Garcia\n"),
266 wxOK
| wxICON_INFORMATION
, this);
269 void MyFrame::OnUDPTest(wxCommandEvent
& WXUNUSED(event
))
271 TestLogger
logtest("UDP test");
275 wxDatagramSocket
sock(addr
);
278 size_t n
= sock
.RecvFrom(addr
, buf
, sizeof(buf
)).LastCount();
281 wxLogMessage("ERROR: failed to receive data");
285 wxLogMessage("Received \"%s\" from %s:%u.",
286 wxString::From8BitData(buf
, n
),
287 addr
.IPAddress(), addr
.Service());
289 for ( size_t i
= 0; i
< n
; i
++ )
292 if ( (c
>= 'A' && c
<= 'M') || (c
>= 'a' && c
<= 'm') )
294 else if ( (c
>= 'N' && c
<= 'Z') || (c
>= 'n' && c
<= 'z') )
298 if ( sock
.SendTo(addr
, buf
, n
).LastCount() != n
)
300 wxLogMessage("ERROR: failed to send data");
305 void MyFrame::OnWaitForAccept(wxCommandEvent
& WXUNUSED(event
))
307 TestLogger
logtest("WaitForAccept() test");
309 wxBusyInfo("Waiting for connection for 10 seconds...", this);
310 if ( m_server
->WaitForAccept(10) )
311 wxLogMessage("Accepted client connection.");
313 wxLogMessage("Connection error or timeout expired.");
316 void MyFrame::Test1(wxSocketBase
*sock
)
318 TestLogger
logtest("Test 1");
320 // Receive data from socket and send it back. We will first
321 // get a byte with the buffer size, so we can specify the
322 // exact size and use the wxSOCKET_WAITALL flag. Also, we
323 // disabled input events so we won't have unwanted reentrance.
324 // This way we can avoid the infamous wxSOCKET_BLOCK flag.
326 sock
->SetFlags(wxSOCKET_WAITALL
);
331 wxCharBuffer
buf(len
);
334 sock
->Read(buf
.data(), len
);
335 wxLogMessage("Got the data, sending it back");
338 sock
->Write(buf
, len
);
341 void MyFrame::Test2(wxSocketBase
*sock
)
345 TestLogger
logtest("Test 2");
347 // We don't need to set flags because ReadMsg and WriteMsg
348 // are not affected by them anyway.
351 wxUint32 len
= sock
->ReadMsg(buf
, sizeof(buf
)).LastCount();
354 wxLogError("Failed to read message.");
358 wxLogMessage("Got \"%s\" from client.", wxString::FromUTF8(buf
, len
));
359 wxLogMessage("Sending the data back");
362 sock
->WriteMsg(buf
, len
);
365 void MyFrame::Test3(wxSocketBase
*sock
)
367 TestLogger
logtest("Test 3");
369 // This test is similar to the first one, but the len is
370 // expressed in kbytes - this tests large data transfers.
372 sock
->SetFlags(wxSOCKET_WAITALL
);
377 wxCharBuffer
buf(len
*1024);
380 sock
->Read(buf
.data(), len
* 1024);
381 wxLogMessage("Got the data, sending it back");
384 sock
->Write(buf
, len
* 1024);
387 void MyFrame::OnServerEvent(wxSocketEvent
& event
)
389 wxString s
= _("OnServerEvent: ");
392 switch(event
.GetSocketEvent())
394 case wxSOCKET_CONNECTION
: s
.Append(_("wxSOCKET_CONNECTION\n")); break;
395 default : s
.Append(_("Unexpected event !\n")); break;
398 m_text
->AppendText(s
);
400 // Accept new connection if there is one in the pending
401 // connections queue, else exit. We use Accept(false) for
402 // non-blocking accept (although if we got here, there
403 // should ALWAYS be a pending connection).
405 sock
= m_server
->Accept(false);
410 if ( !sock
->GetPeer(addr
) )
412 wxLogMessage("New connection from unknown client accepted.");
416 wxLogMessage("New client connection from %s:%u accepted",
417 addr
.IPAddress(), addr
.Service());
422 wxLogMessage("Error: couldn't accept a new connection");
426 sock
->SetEventHandler(*this, SOCKET_ID
);
427 sock
->SetNotify(wxSOCKET_INPUT_FLAG
| wxSOCKET_LOST_FLAG
);
434 void MyFrame::OnSocketEvent(wxSocketEvent
& event
)
436 wxString s
= _("OnSocketEvent: ");
437 wxSocketBase
*sock
= event
.GetSocket();
439 // First, print a message
440 switch(event
.GetSocketEvent())
442 case wxSOCKET_INPUT
: s
.Append(_("wxSOCKET_INPUT\n")); break;
443 case wxSOCKET_LOST
: s
.Append(_("wxSOCKET_LOST\n")); break;
444 default : s
.Append(_("Unexpected event !\n")); break;
447 m_text
->AppendText(s
);
449 // Now we process the event
450 switch(event
.GetSocketEvent())
454 // We disable input events, so that the test doesn't trigger
455 // wxSocketEvent again.
456 sock
->SetNotify(wxSOCKET_LOST_FLAG
);
458 // Which test are we going to run?
464 case 0xBE: Test1(sock
); break;
465 case 0xCE: Test2(sock
); break;
466 case 0xDE: Test3(sock
); break;
468 wxLogMessage("Unknown test id received from client");
471 // Enable input events again.
472 sock
->SetNotify(wxSOCKET_LOST_FLAG
| wxSOCKET_INPUT_FLAG
);
479 // Destroy() should be used instead of delete wherever possible,
480 // due to the fact that wxSocket uses 'delayed events' (see the
481 // documentation for wxPostEvent) and we don't want an event to
482 // arrive to the event handler (the frame, here) after the socket
483 // has been deleted. Also, we might be doing some other thing with
484 // the socket at the same time; for example, we might be in the
485 // middle of a test or something. Destroy() takes care of all
488 wxLogMessage("Deleting socket.");
498 // convenience functions
500 void MyFrame::UpdateStatusBar()
504 s
.Printf(_("%d clients connected"), m_numClients
);
506 #endif // wxUSE_STATUSBAR