]>
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
) )
223 wxLogMessage("ERROR: couldn't get the address we bound to");
225 wxLogMessage("Server listening at %s:%u",
226 addrReal
.IPAddress(), addrReal
.Service());
228 // Setup the event handler and subscribe to connection events
229 m_server
->SetEventHandler(*this, SERVER_ID
);
230 m_server
->SetNotify(wxSOCKET_CONNECTION_FLAG
);
231 m_server
->Notify(true);
240 // No delayed deletion here, as the frame is dying anyway
246 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
248 // true is to force the frame to close
252 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
254 wxMessageBox(_("wxSocket demo: Server\n(c) 1999 Guillermo Rodriguez Garcia\n"),
256 wxOK
| wxICON_INFORMATION
, this);
259 void MyFrame::OnUDPTest(wxCommandEvent
& WXUNUSED(event
))
261 TestLogger
logtest("UDP test");
265 wxDatagramSocket
sock(addr
);
268 size_t n
= sock
.RecvFrom(addr
, buf
, sizeof(buf
)).LastCount();
271 wxLogMessage("ERROR: failed to receive data");
275 wxLogMessage("Received \"%s\" from %s:%u.",
276 wxString::From8BitData(buf
, n
),
277 addr
.IPAddress(), addr
.Service());
279 for ( size_t i
= 0; i
< n
; i
++ )
282 if ( (c
>= 'A' && c
<= 'M') || (c
>= 'a' && c
<= 'm') )
284 else if ( (c
>= 'N' && c
<= 'Z') || (c
>= 'n' && c
<= 'z') )
288 if ( sock
.SendTo(addr
, buf
, n
).LastCount() != n
)
290 wxLogMessage("ERROR: failed to send data");
295 void MyFrame::Test1(wxSocketBase
*sock
)
297 TestLogger
logtest("Test 1");
299 // Receive data from socket and send it back. We will first
300 // get a byte with the buffer size, so we can specify the
301 // exact size and use the wxSOCKET_WAITALL flag. Also, we
302 // disabled input events so we won't have unwanted reentrance.
303 // This way we can avoid the infamous wxSOCKET_BLOCK flag.
305 sock
->SetFlags(wxSOCKET_WAITALL
);
310 wxCharBuffer
buf(len
);
313 sock
->Read(buf
.data(), len
);
314 wxLogMessage("Got the data, sending it back");
317 sock
->Write(buf
, len
);
320 void MyFrame::Test2(wxSocketBase
*sock
)
324 TestLogger
logtest("Test 2");
326 // We don't need to set flags because ReadMsg and WriteMsg
327 // are not affected by them anyway.
330 wxUint32 len
= sock
->ReadMsg(buf
, sizeof(buf
)).LastCount();
333 wxLogError("Failed to read message.");
337 wxLogMessage("Got \"%s\" from client.", wxString::FromUTF8(buf
, len
));
338 wxLogMessage("Sending the data back");
341 sock
->WriteMsg(buf
, len
);
344 void MyFrame::Test3(wxSocketBase
*sock
)
346 TestLogger
logtest("Test 3");
348 // This test is similar to the first one, but the len is
349 // expressed in kbytes - this tests large data transfers.
351 sock
->SetFlags(wxSOCKET_WAITALL
);
356 wxCharBuffer
buf(len
*1024);
359 sock
->Read(buf
.data(), len
* 1024);
360 wxLogMessage("Got the data, sending it back");
363 sock
->Write(buf
, len
* 1024);
366 void MyFrame::OnServerEvent(wxSocketEvent
& event
)
368 wxString s
= _("OnServerEvent: ");
371 switch(event
.GetSocketEvent())
373 case wxSOCKET_CONNECTION
: s
.Append(_("wxSOCKET_CONNECTION\n")); break;
374 default : s
.Append(_("Unexpected event !\n")); break;
377 m_text
->AppendText(s
);
379 // Accept new connection if there is one in the pending
380 // connections queue, else exit. We use Accept(false) for
381 // non-blocking accept (although if we got here, there
382 // should ALWAYS be a pending connection).
384 sock
= m_server
->Accept(false);
389 if ( !sock
->GetPeer(addr
) )
390 wxLogMessage("New connection from unknown client accepted.");
392 wxLogMessage("New client connection from %s:%u accepted",
393 addr
.IPAddress(), addr
.Service());
397 wxLogMessage("Error: couldn't accept a new connection");
401 sock
->SetEventHandler(*this, SOCKET_ID
);
402 sock
->SetNotify(wxSOCKET_INPUT_FLAG
| wxSOCKET_LOST_FLAG
);
409 void MyFrame::OnSocketEvent(wxSocketEvent
& event
)
411 wxString s
= _("OnSocketEvent: ");
412 wxSocketBase
*sock
= event
.GetSocket();
414 // First, print a message
415 switch(event
.GetSocketEvent())
417 case wxSOCKET_INPUT
: s
.Append(_("wxSOCKET_INPUT\n")); break;
418 case wxSOCKET_LOST
: s
.Append(_("wxSOCKET_LOST\n")); break;
419 default : s
.Append(_("Unexpected event !\n")); break;
422 m_text
->AppendText(s
);
424 // Now we process the event
425 switch(event
.GetSocketEvent())
429 // We disable input events, so that the test doesn't trigger
430 // wxSocketEvent again.
431 sock
->SetNotify(wxSOCKET_LOST_FLAG
);
433 // Which test are we going to run?
439 case 0xBE: Test1(sock
); break;
440 case 0xCE: Test2(sock
); break;
441 case 0xDE: Test3(sock
); break;
443 wxLogMessage("Unknown test id received from client");
446 // Enable input events again.
447 sock
->SetNotify(wxSOCKET_LOST_FLAG
| wxSOCKET_INPUT_FLAG
);
454 // Destroy() should be used instead of delete wherever possible,
455 // due to the fact that wxSocket uses 'delayed events' (see the
456 // documentation for wxPostEvent) and we don't want an event to
457 // arrive to the event handler (the frame, here) after the socket
458 // has been deleted. Also, we might be doing some other thing with
459 // the socket at the same time; for example, we might be in the
460 // middle of a test or something. Destroy() takes care of all
463 wxLogMessage("Deleting socket.");
473 // convenience functions
475 void MyFrame::UpdateStatusBar()
479 s
.Printf(_("%d clients connected"), m_numClients
);
481 #endif // wxUSE_STATUSBAR