1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Client 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 #include "wx/sstream.h"
37 // --------------------------------------------------------------------------
39 // --------------------------------------------------------------------------
41 // the application icon
42 #ifndef wxHAS_IMAGES_IN_RESOURCES
43 #include "../sample.xpm"
46 // --------------------------------------------------------------------------
48 // --------------------------------------------------------------------------
50 // Define a new application type
51 class MyApp
: public wxApp
54 virtual bool OnInit();
57 // Define a new frame type: this is going to be our main frame
58 class MyFrame
: public wxFrame
64 // event handlers for File menu
65 void OnQuit(wxCommandEvent
& event
);
66 void OnAbout(wxCommandEvent
& event
);
68 // event handlers for Socket menu
69 void OnOpenConnection(wxCommandEvent
& event
);
70 void OnTest1(wxCommandEvent
& event
);
71 void OnTest2(wxCommandEvent
& event
);
72 void OnTest3(wxCommandEvent
& event
);
73 void OnCloseConnection(wxCommandEvent
& event
);
76 // event handlers for Protocols menu
77 void OnTestURL(wxCommandEvent
& event
);
80 void OnOpenConnectionIPv6(wxCommandEvent
& event
);
83 void OpenConnection(wxSockAddress::Family family
);
85 // event handlers for DatagramSocket menu (stub)
86 void OnDatagram(wxCommandEvent
& event
);
88 // socket event handler
89 void OnSocketEvent(wxSocketEvent
& event
);
91 // convenience functions
92 void UpdateStatusBar();
95 wxSocketClient
*m_sock
;
99 wxMenu
*m_menuDatagramSocket
;
100 wxMenu
*m_menuProtocols
;
101 wxMenuBar
*m_menuBar
;
104 // any class wishing to process wxWidgets events must use this macro
105 DECLARE_EVENT_TABLE()
108 // simple helper class to log start and end of each test
112 TestLogger(const wxString
& name
) : m_name(name
)
114 wxLogMessage("=== %s test begins ===", m_name
);
119 wxLogMessage("=== %s test ends ===", m_name
);
123 const wxString m_name
;
126 // --------------------------------------------------------------------------
128 // --------------------------------------------------------------------------
130 // IDs for the controls and the menu commands
134 CLIENT_QUIT
= wxID_EXIT
,
135 CLIENT_ABOUT
= wxID_ABOUT
,
153 // --------------------------------------------------------------------------
154 // event tables and other macros for wxWidgets
155 // --------------------------------------------------------------------------
157 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
158 EVT_MENU(CLIENT_QUIT
, MyFrame::OnQuit
)
159 EVT_MENU(CLIENT_ABOUT
, MyFrame::OnAbout
)
160 EVT_MENU(CLIENT_OPEN
, MyFrame::OnOpenConnection
)
162 EVT_MENU(CLIENT_OPENIPV6
, MyFrame::OnOpenConnectionIPv6
)
164 EVT_MENU(CLIENT_TEST1
, MyFrame::OnTest1
)
165 EVT_MENU(CLIENT_TEST2
, MyFrame::OnTest2
)
166 EVT_MENU(CLIENT_TEST3
, MyFrame::OnTest3
)
167 EVT_MENU(CLIENT_CLOSE
, MyFrame::OnCloseConnection
)
168 EVT_MENU(CLIENT_DGRAM
, MyFrame::OnDatagram
)
170 EVT_MENU(CLIENT_TESTURL
, MyFrame::OnTestURL
)
172 EVT_SOCKET(SOCKET_ID
, MyFrame::OnSocketEvent
)
177 // ==========================================================================
179 // ==========================================================================
181 // --------------------------------------------------------------------------
182 // the application class
183 // --------------------------------------------------------------------------
187 if ( !wxApp::OnInit() )
190 // Create the main application window
191 MyFrame
*frame
= new MyFrame();
200 // --------------------------------------------------------------------------
202 // --------------------------------------------------------------------------
205 MyFrame::MyFrame() : wxFrame((wxFrame
*)NULL
, wxID_ANY
,
206 _("wxSocket demo: Client"),
207 wxDefaultPosition
, wxSize(300, 200))
209 // Give the frame an icon
210 SetIcon(wxICON(sample
));
213 m_menuFile
= new wxMenu();
214 m_menuFile
->Append(CLIENT_ABOUT
, _("&About\tCtrl-A"), _("Show about dialog"));
215 m_menuFile
->AppendSeparator();
216 m_menuFile
->Append(CLIENT_QUIT
, _("E&xit\tAlt-X"), _("Quit client"));
218 m_menuSocket
= new wxMenu();
219 m_menuSocket
->Append(CLIENT_OPEN
, _("&Open session\tCtrl-O"), _("Connect to server"));
221 m_menuSocket
->Append(CLIENT_OPENIPV6
, _("&Open session(IPv6)\tShift-Ctrl-O"), _("Connect to server(IPv6)"));
223 m_menuSocket
->AppendSeparator();
224 m_menuSocket
->Append(CLIENT_TEST1
, _("Test &1\tCtrl-F1"), _("Test basic functionality"));
225 m_menuSocket
->Append(CLIENT_TEST2
, _("Test &2\tCtrl-F2"), _("Test ReadMsg and WriteMsg"));
226 m_menuSocket
->Append(CLIENT_TEST3
, _("Test &3\tCtrl-F3"), _("Test large data transfer"));
227 m_menuSocket
->AppendSeparator();
228 m_menuSocket
->Append(CLIENT_CLOSE
, _("&Close session\tCtrl-Q"), _("Close connection"));
230 m_menuDatagramSocket
= new wxMenu();
231 m_menuDatagramSocket
->Append(CLIENT_DGRAM
, _("&Datagram test\tCtrl-D"), _("Test UDP sockets"));
234 m_menuProtocols
= new wxMenu();
235 m_menuProtocols
->Append(CLIENT_TESTURL
, _("Test URL\tCtrl-U"),
236 _("Get data from the specified URL"));
239 // Append menus to the menubar
240 m_menuBar
= new wxMenuBar();
241 m_menuBar
->Append(m_menuFile
, _("&File"));
242 m_menuBar
->Append(m_menuSocket
, _("&TCP"));
243 m_menuBar
->Append(m_menuDatagramSocket
, _("&UDP"));
245 m_menuBar
->Append(m_menuProtocols
, _("&Protocols"));
247 SetMenuBar(m_menuBar
);
252 #endif // wxUSE_STATUSBAR
254 // Make a textctrl for logging
255 m_text
= new wxTextCtrl(this, wxID_ANY
,
256 _("Welcome to wxSocket demo: Client\nClient ready\n"),
257 wxDefaultPosition
, wxDefaultSize
,
258 wxTE_MULTILINE
| wxTE_READONLY
);
259 delete wxLog::SetActiveTarget(new wxLogTextCtrl(m_text
));
262 m_sock
= new wxSocketClient();
264 // Setup the event handler and subscribe to most events
265 m_sock
->SetEventHandler(*this, SOCKET_ID
);
266 m_sock
->SetNotify(wxSOCKET_CONNECTION_FLAG
|
267 wxSOCKET_INPUT_FLAG
|
269 m_sock
->Notify(true);
277 // No delayed deletion here, as the frame is dying anyway
283 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
285 // true is to force the frame to close
289 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
291 wxMessageBox(_("wxSocket demo: Client\n(c) 1999 Guillermo Rodriguez Garcia\n"),
293 wxOK
| wxICON_INFORMATION
, this);
296 void MyFrame::OnOpenConnection(wxCommandEvent
& WXUNUSED(event
))
298 OpenConnection(wxSockAddress::IPV4
);
301 void MyFrame::OnOpenConnectionIPv6(wxCommandEvent
& WXUNUSED(event
))
303 OpenConnection(wxSockAddress::IPV6
);
307 void MyFrame::OpenConnection(wxSockAddress::Family family
)
309 wxUnusedVar(family
); // unused in !wxUSE_IPV6 case
315 if ( family
== wxSockAddress::IPV6
)
321 m_menuSocket
->Enable(CLIENT_OPEN
, false);
323 m_menuSocket
->Enable(CLIENT_OPENIPV6
, false);
325 m_menuSocket
->Enable(CLIENT_CLOSE
, false);
327 // Ask user for server address
328 wxString hostname
= wxGetTextFromUser(
329 _("Enter the address of the wxSocket demo server:"),
332 if ( hostname
.empty() )
335 addr
->Hostname(hostname
);
338 // we connect asynchronously and will get a wxSOCKET_CONNECTION event when
339 // the connection is really established
341 // if you want to make sure that connection is established right here you
342 // could call WaitOnConnect(timeout) instead
343 wxLogMessage("Trying to connect to %s:%d", hostname
, addr
->Service());
345 m_sock
->Connect(*addr
, false);
348 void MyFrame::OnTest1(wxCommandEvent
& WXUNUSED(event
))
350 // Disable socket menu entries (exception: Close Session)
354 m_text
->AppendText(_("\n=== Test 1 begins ===\n"));
356 // Tell the server which test we are running
357 unsigned char c
= 0xBE;
358 m_sock
->Write(&c
, 1);
360 // Send some data and read it back. We know the size of the
361 // buffer, so we can specify the exact number of bytes to be
362 // sent or received and use the wxSOCKET_WAITALL flag. Also,
363 // we have disabled menu entries which could interfere with
364 // the test, so we can safely avoid the wxSOCKET_BLOCK flag.
366 // First we send a byte with the length of the string, then
367 // we send the string itself (do NOT try to send any integral
368 // value larger than a byte "as is" across the network, or
369 // you might be in trouble! Ever heard about big and little
370 // endian computers?)
372 m_sock
->SetFlags(wxSOCKET_WAITALL
);
374 const char *buf1
= "Test string (less than 256 chars!)";
375 unsigned char len
= (unsigned char)(wxStrlen(buf1
) + 1);
376 wxCharBuffer
buf2(wxStrlen(buf1
));
378 m_text
->AppendText(_("Sending a test buffer to the server ..."));
379 m_sock
->Write(&len
, 1);
380 m_sock
->Write(buf1
, len
);
381 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
383 m_text
->AppendText(_("Receiving the buffer back from server ..."));
384 m_sock
->Read(buf2
.data(), len
);
385 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
387 m_text
->AppendText(_("Comparing the two buffers ..."));
388 if (memcmp(buf1
, buf2
, len
) != 0)
390 m_text
->AppendText(_("failed!\n"));
391 m_text
->AppendText(_("Test 1 failed !\n"));
395 m_text
->AppendText(_("done\n"));
396 m_text
->AppendText(_("Test 1 passed !\n"));
398 m_text
->AppendText(_("=== Test 1 ends ===\n"));
404 void MyFrame::OnTest2(wxCommandEvent
& WXUNUSED(event
))
406 // Disable socket menu entries (exception: Close Session)
410 m_text
->AppendText(_("\n=== Test 2 begins ===\n"));
412 // Tell the server which test we are running
413 unsigned char c
= 0xCE;
414 m_sock
->Write(&c
, 1);
416 // Here we use ReadMsg and WriteMsg to send messages with
417 // a header with size information. Also, the reception is
418 // event triggered, so we test input events as well.
420 // We need to set no flags here (ReadMsg and WriteMsg are
421 // not affected by flags)
423 m_sock
->SetFlags(wxSOCKET_WAITALL
);
425 wxString s
= wxGetTextFromUser(
426 _("Enter an arbitrary string to send to the server:"),
428 _("Yes I like wxWidgets!"));
430 const wxScopedCharBuffer
msg1(s
.utf8_str());
431 size_t len
= wxStrlen(msg1
) + 1;
432 wxCharBuffer
msg2(wxStrlen(msg1
));
434 m_text
->AppendText(_("Sending the string with WriteMsg ..."));
435 m_sock
->WriteMsg(msg1
, len
);
436 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
437 m_text
->AppendText(_("Waiting for an event (timeout = 2 sec)\n"));
439 // Wait until data available (will also return if the connection is lost)
440 m_sock
->WaitForRead(2);
442 if (m_sock
->IsData())
444 m_text
->AppendText(_("Reading the string back with ReadMsg ..."));
445 m_sock
->ReadMsg(msg2
.data(), len
);
446 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
447 m_text
->AppendText(_("Comparing the two buffers ..."));
448 if (memcmp(msg1
, msg2
, len
) != 0)
450 m_text
->AppendText(_("failed!\n"));
451 m_text
->AppendText(_("Test 2 failed !\n"));
455 m_text
->AppendText(_("done\n"));
456 m_text
->AppendText(_("Test 2 passed !\n"));
460 m_text
->AppendText(_("Timeout ! Test 2 failed.\n"));
462 m_text
->AppendText(_("=== Test 2 ends ===\n"));
468 void MyFrame::OnTest3(wxCommandEvent
& WXUNUSED(event
))
470 // Disable socket menu entries (exception: Close Session)
474 m_text
->AppendText(_("\n=== Test 3 begins ===\n"));
476 // Tell the server which test we are running
477 unsigned char c
= 0xDE;
478 m_sock
->Write(&c
, 1);
480 // This test also is similar to the first one but it sends a
481 // large buffer so that wxSocket is actually forced to split
482 // it into pieces and take care of sending everything before
485 m_sock
->SetFlags(wxSOCKET_WAITALL
);
487 // Note that len is in kbytes here!
488 const unsigned char len
= 32;
489 wxCharBuffer
buf1(len
* 1024),
492 for (size_t i
= 0; i
< len
* 1024; i
++)
493 buf1
.data()[i
] = (char)(i
% 256);
495 m_text
->AppendText(_("Sending a large buffer (32K) to the server ..."));
496 m_sock
->Write(&len
, 1);
497 m_sock
->Write(buf1
, len
* 1024);
498 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
500 m_text
->AppendText(_("Receiving the buffer back from server ..."));
501 m_sock
->Read(buf2
.data(), len
* 1024);
502 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
504 m_text
->AppendText(_("Comparing the two buffers ..."));
505 if (memcmp(buf1
, buf2
, len
) != 0)
507 m_text
->AppendText(_("failed!\n"));
508 m_text
->AppendText(_("Test 3 failed !\n"));
512 m_text
->AppendText(_("done\n"));
513 m_text
->AppendText(_("Test 3 passed !\n"));
515 m_text
->AppendText(_("=== Test 3 ends ===\n"));
521 void MyFrame::OnCloseConnection(wxCommandEvent
& WXUNUSED(event
))
527 void MyFrame::OnDatagram(wxCommandEvent
& WXUNUSED(event
))
529 wxString hostname
= wxGetTextFromUser
531 "Enter the address of the wxSocket demo server:",
535 if ( hostname
.empty() )
538 TestLogger
logtest("UDP");
540 wxIPV4address addrLocal
;
541 addrLocal
.Hostname();
542 wxDatagramSocket
sock(addrLocal
);
545 wxLogMessage("ERROR: failed to create UDP socket");
549 wxLogMessage("Created UDP socket at %s:%u",
550 addrLocal
.IPAddress(), addrLocal
.Service());
552 wxIPV4address addrPeer
;
553 addrPeer
.Hostname(hostname
);
554 addrPeer
.Service(3000);
556 wxLogMessage("Testing UDP with peer at %s:%u",
557 addrPeer
.IPAddress(), addrPeer
.Service());
559 char buf
[] = "Uryyb sebz pyvrag!";
560 if ( sock
.SendTo(addrPeer
, buf
, sizeof(buf
)).LastCount() != sizeof(buf
) )
562 wxLogMessage("ERROR: failed to send data");
566 if ( sock
.RecvFrom(addrPeer
, buf
, sizeof(buf
)).LastCount() != sizeof(buf
) )
568 wxLogMessage("ERROR: failed to receive data");
572 wxLogMessage("Received \"%s\" from %s:%u.",
573 wxString::From8BitData(buf
, sock
.LastCount()),
574 addrPeer
.IPAddress(), addrPeer
.Service());
579 void MyFrame::OnTestURL(wxCommandEvent
& WXUNUSED(event
))
582 static wxString
s_urlname("http://www.google.com/");
583 wxString urlname
= wxGetTextFromUser
585 _("Enter an URL to get"),
589 if ( urlname
.empty() )
590 return; // cancelled by user
595 TestLogger
logtest("URL");
599 if ( url
.GetError() != wxURL_NOERR
)
601 wxLogError("Failed to parse URL \"%s\"", urlname
);
605 // Try to get the input stream (connects to the given URL)
606 wxLogMessage("Establishing connection to \"%s\"...", urlname
);
607 const std::auto_ptr
<wxInputStream
> data(url
.GetInputStream());
610 wxLogError("Failed to retrieve URL \"%s\"", urlname
);
614 // Print the contents type and file size
615 wxLogMessage("Contents type: %s\nFile size: %lu\nStarting to download...",
616 url
.GetProtocol().GetContentType(),
617 static_cast<unsigned long>( data
->GetSize() ));
620 wxStringOutputStream sout
;
621 if ( data
->Read(sout
).GetLastError() != wxSTREAM_EOF
)
623 wxLogError("Error reading the input stream.");
626 wxLogMessage("Text retrieved from URL \"%s\" follows:\n%s",
627 urlname
, sout
.GetString());
632 void MyFrame::OnSocketEvent(wxSocketEvent
& event
)
634 switch ( event
.GetSocketEvent() )
637 wxLogMessage("Input available on the socket");
641 wxLogMessage("Socket connection was unexpectedly lost.");
645 case wxSOCKET_CONNECTION
:
646 wxLogMessage("... socket is now connected.");
651 wxLogMessage("Unknown socket event!!!");
656 // convenience functions
658 void MyFrame::UpdateStatusBar()
663 if (!m_sock
->IsConnected())
675 m_sock
->GetPeer(addr
);
676 s
.Printf("%s : %d", addr
.Hostname(), addr
.Service());
680 #endif // wxUSE_STATUSBAR
682 m_menuSocket
->Enable(CLIENT_OPEN
, !m_sock
->IsConnected() && !m_busy
);
684 m_menuSocket
->Enable(CLIENT_OPENIPV6
, !m_sock
->IsConnected() && !m_busy
);
686 m_menuSocket
->Enable(CLIENT_TEST1
, m_sock
->IsConnected() && !m_busy
);
687 m_menuSocket
->Enable(CLIENT_TEST2
, m_sock
->IsConnected() && !m_busy
);
688 m_menuSocket
->Enable(CLIENT_TEST3
, m_sock
->IsConnected() && !m_busy
);
689 m_menuSocket
->Enable(CLIENT_CLOSE
, m_sock
->IsConnected());