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 #if !defined(__WXMSW__) && !defined(__WXPM__)
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();
193 // Show it and tell the application that it's our main window
201 // --------------------------------------------------------------------------
203 // --------------------------------------------------------------------------
206 MyFrame::MyFrame() : wxFrame((wxFrame
*)NULL
, wxID_ANY
,
207 _("wxSocket demo: Client"),
208 wxDefaultPosition
, wxSize(300, 200))
210 // Give the frame an icon
211 SetIcon(wxICON(sample
));
214 m_menuFile
= new wxMenu();
215 m_menuFile
->Append(CLIENT_ABOUT
, _("&About...\tCtrl-A"), _("Show about dialog"));
216 m_menuFile
->AppendSeparator();
217 m_menuFile
->Append(CLIENT_QUIT
, _("E&xit\tAlt-X"), _("Quit client"));
219 m_menuSocket
= new wxMenu();
220 m_menuSocket
->Append(CLIENT_OPEN
, _("&Open session\tCtrl-O"), _("Connect to server"));
222 m_menuSocket
->Append(CLIENT_OPENIPV6
, _("&Open session(IPv6)\tShift-Ctrl-O"), _("Connect to server(IPv6)"));
224 m_menuSocket
->AppendSeparator();
225 m_menuSocket
->Append(CLIENT_TEST1
, _("Test &1\tCtrl-F1"), _("Test basic functionality"));
226 m_menuSocket
->Append(CLIENT_TEST2
, _("Test &2\tCtrl-F2"), _("Test ReadMsg and WriteMsg"));
227 m_menuSocket
->Append(CLIENT_TEST3
, _("Test &3\tCtrl-F3"), _("Test large data transfer"));
228 m_menuSocket
->AppendSeparator();
229 m_menuSocket
->Append(CLIENT_CLOSE
, _("&Close session\tCtrl-Q"), _("Close connection"));
231 m_menuDatagramSocket
= new wxMenu();
232 m_menuDatagramSocket
->Append(CLIENT_DGRAM
, _("&Datagram test\tCtrl-D"), _("Test UDP sockets"));
235 m_menuProtocols
= new wxMenu();
236 m_menuProtocols
->Append(CLIENT_TESTURL
, _("Test URL\tCtrl-U"),
237 _("Get data from the specified URL"));
240 // Append menus to the menubar
241 m_menuBar
= new wxMenuBar();
242 m_menuBar
->Append(m_menuFile
, _("&File"));
243 m_menuBar
->Append(m_menuSocket
, _("&TCP"));
244 m_menuBar
->Append(m_menuDatagramSocket
, _("&UDP"));
246 m_menuBar
->Append(m_menuProtocols
, _("&Protocols"));
248 SetMenuBar(m_menuBar
);
253 #endif // wxUSE_STATUSBAR
255 // Make a textctrl for logging
256 m_text
= new wxTextCtrl(this, wxID_ANY
,
257 _("Welcome to wxSocket demo: Client\nClient ready\n"),
258 wxDefaultPosition
, wxDefaultSize
,
259 wxTE_MULTILINE
| wxTE_READONLY
);
260 delete wxLog::SetActiveTarget(new wxLogTextCtrl(m_text
));
263 m_sock
= new wxSocketClient();
265 // Setup the event handler and subscribe to most events
266 m_sock
->SetEventHandler(*this, SOCKET_ID
);
267 m_sock
->SetNotify(wxSOCKET_CONNECTION_FLAG
|
268 wxSOCKET_INPUT_FLAG
|
270 m_sock
->Notify(true);
278 // No delayed deletion here, as the frame is dying anyway
284 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
286 // true is to force the frame to close
290 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
292 wxMessageBox(_("wxSocket demo: Client\n(c) 1999 Guillermo Rodriguez Garcia\n"),
294 wxOK
| wxICON_INFORMATION
, this);
297 void MyFrame::OnOpenConnection(wxCommandEvent
& WXUNUSED(event
))
299 OpenConnection(wxSockAddress::IPV4
);
302 void MyFrame::OnOpenConnectionIPv6(wxCommandEvent
& WXUNUSED(event
))
304 OpenConnection(wxSockAddress::IPV6
);
308 void MyFrame::OpenConnection(wxSockAddress::Family family
)
310 wxUnusedVar(family
); // unused in !wxUSE_IPV6 case
316 if ( family
== wxSockAddress::IPV6
)
322 m_menuSocket
->Enable(CLIENT_OPEN
, false);
324 m_menuSocket
->Enable(CLIENT_OPENIPV6
, false);
326 m_menuSocket
->Enable(CLIENT_CLOSE
, false);
328 // Ask user for server address
329 wxString hostname
= wxGetTextFromUser(
330 _("Enter the address of the wxSocket demo server:"),
333 if ( hostname
.empty() )
336 addr
->Hostname(hostname
);
339 // we connect asynchronously and will get a wxSOCKET_CONNECTION event when
340 // the connection is really established
342 // if you want to make sure that connection is established right here you
343 // could call WaitOnConnect(timeout) instead
344 wxLogMessage("Trying to connect to %s:%d", hostname
, addr
->Service());
346 m_sock
->Connect(*addr
, false);
349 void MyFrame::OnTest1(wxCommandEvent
& WXUNUSED(event
))
351 // Disable socket menu entries (exception: Close Session)
355 m_text
->AppendText(_("\n=== Test 1 begins ===\n"));
357 // Tell the server which test we are running
358 unsigned char c
= 0xBE;
359 m_sock
->Write(&c
, 1);
361 // Send some data and read it back. We know the size of the
362 // buffer, so we can specify the exact number of bytes to be
363 // sent or received and use the wxSOCKET_WAITALL flag. Also,
364 // we have disabled menu entries which could interfere with
365 // the test, so we can safely avoid the wxSOCKET_BLOCK flag.
367 // First we send a byte with the length of the string, then
368 // we send the string itself (do NOT try to send any integral
369 // value larger than a byte "as is" across the network, or
370 // you might be in trouble! Ever heard about big and little
371 // endian computers?)
373 m_sock
->SetFlags(wxSOCKET_WAITALL
);
375 const char *buf1
= "Test string (less than 256 chars!)";
376 unsigned char len
= (unsigned char)(wxStrlen(buf1
) + 1);
377 wxCharBuffer
buf2(wxStrlen(buf1
));
379 m_text
->AppendText(_("Sending a test buffer to the server ..."));
380 m_sock
->Write(&len
, 1);
381 m_sock
->Write(buf1
, len
);
382 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
384 m_text
->AppendText(_("Receiving the buffer back from server ..."));
385 m_sock
->Read(buf2
.data(), len
);
386 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
388 m_text
->AppendText(_("Comparing the two buffers ..."));
389 if (memcmp(buf1
, buf2
, len
) != 0)
391 m_text
->AppendText(_("failed!\n"));
392 m_text
->AppendText(_("Test 1 failed !\n"));
396 m_text
->AppendText(_("done\n"));
397 m_text
->AppendText(_("Test 1 passed !\n"));
399 m_text
->AppendText(_("=== Test 1 ends ===\n"));
405 void MyFrame::OnTest2(wxCommandEvent
& WXUNUSED(event
))
407 // Disable socket menu entries (exception: Close Session)
411 m_text
->AppendText(_("\n=== Test 2 begins ===\n"));
413 // Tell the server which test we are running
414 unsigned char c
= 0xCE;
415 m_sock
->Write(&c
, 1);
417 // Here we use ReadMsg and WriteMsg to send messages with
418 // a header with size information. Also, the reception is
419 // event triggered, so we test input events as well.
421 // We need to set no flags here (ReadMsg and WriteMsg are
422 // not affected by flags)
424 m_sock
->SetFlags(wxSOCKET_WAITALL
);
426 wxString s
= wxGetTextFromUser(
427 _("Enter an arbitrary string to send to the server:"),
429 _("Yes I like wxWidgets!"));
431 const wxScopedCharBuffer
msg1(s
.utf8_str());
432 size_t len
= wxStrlen(msg1
) + 1;
433 wxCharBuffer
msg2(wxStrlen(msg1
));
435 m_text
->AppendText(_("Sending the string with WriteMsg ..."));
436 m_sock
->WriteMsg(msg1
, len
);
437 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
438 m_text
->AppendText(_("Waiting for an event (timeout = 2 sec)\n"));
440 // Wait until data available (will also return if the connection is lost)
441 m_sock
->WaitForRead(2);
443 if (m_sock
->IsData())
445 m_text
->AppendText(_("Reading the string back with ReadMsg ..."));
446 m_sock
->ReadMsg(msg2
.data(), len
);
447 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
448 m_text
->AppendText(_("Comparing the two buffers ..."));
449 if (memcmp(msg1
, msg2
, len
) != 0)
451 m_text
->AppendText(_("failed!\n"));
452 m_text
->AppendText(_("Test 2 failed !\n"));
456 m_text
->AppendText(_("done\n"));
457 m_text
->AppendText(_("Test 2 passed !\n"));
461 m_text
->AppendText(_("Timeout ! Test 2 failed.\n"));
463 m_text
->AppendText(_("=== Test 2 ends ===\n"));
469 void MyFrame::OnTest3(wxCommandEvent
& WXUNUSED(event
))
471 // Disable socket menu entries (exception: Close Session)
475 m_text
->AppendText(_("\n=== Test 3 begins ===\n"));
477 // Tell the server which test we are running
478 unsigned char c
= 0xDE;
479 m_sock
->Write(&c
, 1);
481 // This test also is similar to the first one but it sends a
482 // large buffer so that wxSocket is actually forced to split
483 // it into pieces and take care of sending everything before
486 m_sock
->SetFlags(wxSOCKET_WAITALL
);
488 // Note that len is in kbytes here!
489 const unsigned char len
= 32;
490 wxCharBuffer
buf1(len
* 1024),
493 for (size_t i
= 0; i
< len
* 1024; i
++)
494 buf1
.data()[i
] = (char)(i
% 256);
496 m_text
->AppendText(_("Sending a large buffer (32K) to the server ..."));
497 m_sock
->Write(&len
, 1);
498 m_sock
->Write(buf1
, len
* 1024);
499 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
501 m_text
->AppendText(_("Receiving the buffer back from server ..."));
502 m_sock
->Read(buf2
.data(), len
* 1024);
503 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
505 m_text
->AppendText(_("Comparing the two buffers ..."));
506 if (memcmp(buf1
, buf2
, len
) != 0)
508 m_text
->AppendText(_("failed!\n"));
509 m_text
->AppendText(_("Test 3 failed !\n"));
513 m_text
->AppendText(_("done\n"));
514 m_text
->AppendText(_("Test 3 passed !\n"));
516 m_text
->AppendText(_("=== Test 3 ends ===\n"));
522 void MyFrame::OnCloseConnection(wxCommandEvent
& WXUNUSED(event
))
528 void MyFrame::OnDatagram(wxCommandEvent
& WXUNUSED(event
))
530 wxString hostname
= wxGetTextFromUser
532 "Enter the address of the wxSocket demo server:",
536 if ( hostname
.empty() )
539 TestLogger
logtest("UDP");
541 wxIPV4address addrLocal
;
542 addrLocal
.Hostname();
543 wxDatagramSocket
sock(addrLocal
);
546 wxLogMessage("ERROR: failed to create UDP socket");
550 wxLogMessage("Created UDP socket at %s:%u",
551 addrLocal
.IPAddress(), addrLocal
.Service());
553 wxIPV4address addrPeer
;
554 addrPeer
.Hostname(hostname
);
555 addrPeer
.Service(3000);
557 wxLogMessage("Testing UDP with peer at %s:%u",
558 addrPeer
.IPAddress(), addrPeer
.Service());
560 char buf
[] = "Uryyb sebz pyvrag!";
561 if ( sock
.SendTo(addrPeer
, buf
, sizeof(buf
)).LastCount() != sizeof(buf
) )
563 wxLogMessage("ERROR: failed to send data");
567 if ( sock
.RecvFrom(addrPeer
, buf
, sizeof(buf
)).LastCount() != sizeof(buf
) )
569 wxLogMessage("ERROR: failed to receive data");
573 wxLogMessage("Received \"%s\" from %s:%u.",
574 wxString::From8BitData(buf
, sock
.LastCount()),
575 addrPeer
.IPAddress(), addrPeer
.Service());
580 void MyFrame::OnTestURL(wxCommandEvent
& WXUNUSED(event
))
583 static wxString
s_urlname("http://www.google.com/");
584 wxString urlname
= wxGetTextFromUser
586 _("Enter an URL to get"),
590 if ( urlname
.empty() )
591 return; // cancelled by user
596 TestLogger
logtest("URL");
600 if ( url
.GetError() != wxURL_NOERR
)
602 wxLogError("Failed to parse URL \"%s\"", urlname
);
606 // Try to get the input stream (connects to the given URL)
607 wxLogMessage("Establishing connection to \"%s\"...", urlname
);
608 const std::auto_ptr
<wxInputStream
> data(url
.GetInputStream());
611 wxLogError("Failed to retrieve URL \"%s\"", urlname
);
615 // Print the contents type and file size
616 wxLogMessage("Contents type: %s\nFile size: %i\nStarting to download...",
617 url
.GetProtocol().GetContentType(),
621 wxStringOutputStream sout
;
622 if ( data
->Read(sout
).GetLastError() != wxSTREAM_EOF
)
624 wxLogError("Error reading the input stream.");
627 wxLogMessage("Text retrieved from URL \"%s\" follows:\n%s",
628 urlname
, sout
.GetString());
633 void MyFrame::OnSocketEvent(wxSocketEvent
& event
)
635 switch ( event
.GetSocketEvent() )
638 wxLogMessage("Input available on the socket");
642 wxLogMessage("Socket connection was unexpectedly lost.");
646 case wxSOCKET_CONNECTION
:
647 wxLogMessage("... socket is now connected.");
652 wxLogMessage("Unknown socket event!!!");
657 // convenience functions
659 void MyFrame::UpdateStatusBar()
664 if (!m_sock
->IsConnected())
676 m_sock
->GetPeer(addr
);
677 s
.Printf("%s : %d", addr
.Hostname(), addr
.Service());
681 #endif // wxUSE_STATUSBAR
683 m_menuSocket
->Enable(CLIENT_OPEN
, !m_sock
->IsConnected() && !m_busy
);
685 m_menuSocket
->Enable(CLIENT_OPENIPV6
, !m_sock
->IsConnected() && !m_busy
);
687 m_menuSocket
->Enable(CLIENT_TEST1
, m_sock
->IsConnected() && !m_busy
);
688 m_menuSocket
->Enable(CLIENT_TEST2
, m_sock
->IsConnected() && !m_busy
);
689 m_menuSocket
->Enable(CLIENT_TEST3
, m_sock
->IsConnected() && !m_busy
);
690 m_menuSocket
->Enable(CLIENT_CLOSE
, m_sock
->IsConnected());