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 #include "mondrian.xpm"
44 // --------------------------------------------------------------------------
46 // --------------------------------------------------------------------------
48 // Define a new application type
49 class MyApp
: public wxApp
52 virtual bool OnInit();
55 // Define a new frame type: this is going to be our main frame
56 class MyFrame
: public wxFrame
62 // event handlers for File menu
63 void OnQuit(wxCommandEvent
& event
);
64 void OnAbout(wxCommandEvent
& event
);
66 // event handlers for Socket menu
67 void OnOpenConnection(wxCommandEvent
& event
);
68 void OnTest1(wxCommandEvent
& event
);
69 void OnTest2(wxCommandEvent
& event
);
70 void OnTest3(wxCommandEvent
& event
);
71 void OnCloseConnection(wxCommandEvent
& event
);
74 // event handlers for Protocols menu
75 void OnTestURL(wxCommandEvent
& event
);
78 void OnOpenConnectionIPv6(wxCommandEvent
& event
);
81 void OpenConnection(wxSockAddress::Family family
);
83 // event handlers for DatagramSocket menu (stub)
84 void OnDatagram(wxCommandEvent
& event
);
86 // socket event handler
87 void OnSocketEvent(wxSocketEvent
& event
);
89 // convenience functions
90 void UpdateStatusBar();
93 wxSocketClient
*m_sock
;
97 wxMenu
*m_menuDatagramSocket
;
98 wxMenu
*m_menuProtocols
;
102 // any class wishing to process wxWidgets events must use this macro
103 DECLARE_EVENT_TABLE()
106 // simple helper class to log start and end of each test
110 TestLogger(const wxString
& name
) : m_name(name
)
112 wxLogMessage("=== %s test begins ===", m_name
);
117 wxLogMessage("=== %s test ends ===", m_name
);
121 const wxString m_name
;
124 // --------------------------------------------------------------------------
126 // --------------------------------------------------------------------------
128 // IDs for the controls and the menu commands
132 CLIENT_QUIT
= wxID_EXIT
,
133 CLIENT_ABOUT
= wxID_ABOUT
,
151 // --------------------------------------------------------------------------
152 // event tables and other macros for wxWidgets
153 // --------------------------------------------------------------------------
155 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
156 EVT_MENU(CLIENT_QUIT
, MyFrame::OnQuit
)
157 EVT_MENU(CLIENT_ABOUT
, MyFrame::OnAbout
)
158 EVT_MENU(CLIENT_OPEN
, MyFrame::OnOpenConnection
)
160 EVT_MENU(CLIENT_OPENIPV6
, MyFrame::OnOpenConnectionIPv6
)
162 EVT_MENU(CLIENT_TEST1
, MyFrame::OnTest1
)
163 EVT_MENU(CLIENT_TEST2
, MyFrame::OnTest2
)
164 EVT_MENU(CLIENT_TEST3
, MyFrame::OnTest3
)
165 EVT_MENU(CLIENT_CLOSE
, MyFrame::OnCloseConnection
)
166 EVT_MENU(CLIENT_DGRAM
, MyFrame::OnDatagram
)
168 EVT_MENU(CLIENT_TESTURL
, MyFrame::OnTestURL
)
170 EVT_SOCKET(SOCKET_ID
, MyFrame::OnSocketEvent
)
175 // ==========================================================================
177 // ==========================================================================
179 // --------------------------------------------------------------------------
180 // the application class
181 // --------------------------------------------------------------------------
185 if ( !wxApp::OnInit() )
188 // Create the main application window
189 MyFrame
*frame
= new MyFrame();
191 // Show it and tell the application that it's our main window
199 // --------------------------------------------------------------------------
201 // --------------------------------------------------------------------------
204 MyFrame::MyFrame() : wxFrame((wxFrame
*)NULL
, wxID_ANY
,
205 _("wxSocket demo: Client"),
206 wxDefaultPosition
, wxSize(300, 200))
208 // Give the frame an icon
209 SetIcon(wxICON(mondrian
));
212 m_menuFile
= new wxMenu();
213 m_menuFile
->Append(CLIENT_ABOUT
, _("&About...\tCtrl-A"), _("Show about dialog"));
214 m_menuFile
->AppendSeparator();
215 m_menuFile
->Append(CLIENT_QUIT
, _("E&xit\tAlt-X"), _("Quit client"));
217 m_menuSocket
= new wxMenu();
218 m_menuSocket
->Append(CLIENT_OPEN
, _("&Open session\tCtrl-O"), _("Connect to server"));
220 m_menuSocket
->Append(CLIENT_OPENIPV6
, _("&Open session(IPv6)\tShift-Ctrl-O"), _("Connect to server(IPv6)"));
222 m_menuSocket
->AppendSeparator();
223 m_menuSocket
->Append(CLIENT_TEST1
, _("Test &1\tCtrl-F1"), _("Test basic functionality"));
224 m_menuSocket
->Append(CLIENT_TEST2
, _("Test &2\tCtrl-F2"), _("Test ReadMsg and WriteMsg"));
225 m_menuSocket
->Append(CLIENT_TEST3
, _("Test &3\tCtrl-F3"), _("Test large data transfer"));
226 m_menuSocket
->AppendSeparator();
227 m_menuSocket
->Append(CLIENT_CLOSE
, _("&Close session\tCtrl-Q"), _("Close connection"));
229 m_menuDatagramSocket
= new wxMenu();
230 m_menuDatagramSocket
->Append(CLIENT_DGRAM
, _("&Datagram test\tCtrl-D"), _("Test UDP sockets"));
233 m_menuProtocols
= new wxMenu();
234 m_menuProtocols
->Append(CLIENT_TESTURL
, _("Test URL\tCtrl-U"),
235 _("Get data from the specified URL"));
238 // Append menus to the menubar
239 m_menuBar
= new wxMenuBar();
240 m_menuBar
->Append(m_menuFile
, _("&File"));
241 m_menuBar
->Append(m_menuSocket
, _("&TCP"));
242 m_menuBar
->Append(m_menuDatagramSocket
, _("&UDP"));
244 m_menuBar
->Append(m_menuProtocols
, _("&Protocols"));
246 SetMenuBar(m_menuBar
);
251 #endif // wxUSE_STATUSBAR
253 // Make a textctrl for logging
254 m_text
= new wxTextCtrl(this, wxID_ANY
,
255 _("Welcome to wxSocket demo: Client\nClient ready\n"),
256 wxDefaultPosition
, wxDefaultSize
,
257 wxTE_MULTILINE
| wxTE_READONLY
);
258 delete wxLog::SetActiveTarget(new wxLogTextCtrl(m_text
));
261 m_sock
= new wxSocketClient();
263 // Setup the event handler and subscribe to most events
264 m_sock
->SetEventHandler(*this, SOCKET_ID
);
265 m_sock
->SetNotify(wxSOCKET_CONNECTION_FLAG
|
266 wxSOCKET_INPUT_FLAG
|
268 m_sock
->Notify(true);
276 // No delayed deletion here, as the frame is dying anyway
282 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
284 // true is to force the frame to close
288 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
290 wxMessageBox(_("wxSocket demo: Client\n(c) 1999 Guillermo Rodriguez Garcia\n"),
292 wxOK
| wxICON_INFORMATION
, this);
295 void MyFrame::OnOpenConnection(wxCommandEvent
& WXUNUSED(event
))
297 OpenConnection(wxSockAddress::IPV4
);
300 void MyFrame::OnOpenConnectionIPv6(wxCommandEvent
& WXUNUSED(event
))
302 OpenConnection(wxSockAddress::IPV6
);
306 void MyFrame::OpenConnection(wxSockAddress::Family family
)
308 wxUnusedVar(family
); // unused in !wxUSE_IPV6 case
314 if ( family
== wxSockAddress::IPV6
)
320 m_menuSocket
->Enable(CLIENT_OPEN
, false);
322 m_menuSocket
->Enable(CLIENT_OPENIPV6
, false);
324 m_menuSocket
->Enable(CLIENT_CLOSE
, false);
326 // Ask user for server address
327 wxString hostname
= wxGetTextFromUser(
328 _("Enter the address of the wxSocket demo server:"),
331 if ( hostname
.empty() )
334 addr
->Hostname(hostname
);
337 // Mini-tutorial for Connect() :-)
338 // ---------------------------
340 // There are two ways to use Connect(): blocking and non-blocking,
341 // depending on the value passed as the 'wait' (2nd) parameter.
343 // Connect(addr, true) will wait until the connection completes,
344 // returning true on success and false on failure. This call blocks
345 // the GUI (this might be changed in future releases to honour the
346 // wxSOCKET_BLOCK flag).
348 // Connect(addr, false) will issue a nonblocking connection request
349 // and return immediately. If the return value is true, then the
350 // connection has been already successfully established. If it is
351 // false, you must wait for the request to complete, either with
352 // WaitOnConnect() or by watching wxSOCKET_CONNECTION / LOST
353 // events (please read the documentation).
355 // WaitOnConnect() itself never blocks the GUI (this might change
356 // in the future to honour the wxSOCKET_BLOCK flag). This call will
357 // return false on timeout, or true if the connection request
358 // completes, which in turn might mean:
360 // a) That the connection was successfully established
361 // b) That the connection request failed (for example, because
362 // it was refused by the peer.
364 // Use IsConnected() to distinguish between these two.
366 // So, in a brief, you should do one of the following things:
368 // For blocking Connect:
370 // bool success = client->Connect(addr, true);
372 // For nonblocking Connect:
374 // client->Connect(addr, false);
376 // bool waitmore = true;
377 // while (! client->WaitOnConnect(seconds, millis) && waitmore )
379 // // possibly give some feedback to the user,
380 // // update waitmore if needed.
382 // bool success = client->IsConnected();
384 // And that's all :-)
386 m_text
->AppendText(_("\nTrying to connect (timeout = 10 sec) ...\n"));
387 m_sock
->Connect(*addr
, false);
388 m_sock
->WaitOnConnect(10);
390 if (m_sock
->IsConnected())
391 m_text
->AppendText(_("Succeeded ! Connection established\n"));
395 m_text
->AppendText(_("Failed ! Unable to connect\n"));
396 wxMessageBox(_("Can't connect to the specified host"), _("Alert !"));
402 void MyFrame::OnTest1(wxCommandEvent
& WXUNUSED(event
))
404 // Disable socket menu entries (exception: Close Session)
408 m_text
->AppendText(_("\n=== Test 1 begins ===\n"));
410 // Tell the server which test we are running
411 unsigned char c
= 0xBE;
412 m_sock
->Write(&c
, 1);
414 // Send some data and read it back. We know the size of the
415 // buffer, so we can specify the exact number of bytes to be
416 // sent or received and use the wxSOCKET_WAITALL flag. Also,
417 // we have disabled menu entries which could interfere with
418 // the test, so we can safely avoid the wxSOCKET_BLOCK flag.
420 // First we send a byte with the length of the string, then
421 // we send the string itself (do NOT try to send any integral
422 // value larger than a byte "as is" across the network, or
423 // you might be in trouble! Ever heard about big and little
424 // endian computers?)
426 m_sock
->SetFlags(wxSOCKET_WAITALL
);
428 const char *buf1
= "Test string (less than 256 chars!)";
429 unsigned char len
= (unsigned char)(wxStrlen(buf1
) + 1);
430 wxCharBuffer
buf2(wxStrlen(buf1
));
432 m_text
->AppendText(_("Sending a test buffer to the server ..."));
433 m_sock
->Write(&len
, 1);
434 m_sock
->Write(buf1
, len
);
435 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
437 m_text
->AppendText(_("Receiving the buffer back from server ..."));
438 m_sock
->Read(buf2
.data(), len
);
439 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
441 m_text
->AppendText(_("Comparing the two buffers ..."));
442 if (memcmp(buf1
, buf2
, len
) != 0)
444 m_text
->AppendText(_("failed!\n"));
445 m_text
->AppendText(_("Test 1 failed !\n"));
449 m_text
->AppendText(_("done\n"));
450 m_text
->AppendText(_("Test 1 passed !\n"));
452 m_text
->AppendText(_("=== Test 1 ends ===\n"));
458 void MyFrame::OnTest2(wxCommandEvent
& WXUNUSED(event
))
460 // Disable socket menu entries (exception: Close Session)
464 m_text
->AppendText(_("\n=== Test 2 begins ===\n"));
466 // Tell the server which test we are running
467 unsigned char c
= 0xCE;
468 m_sock
->Write(&c
, 1);
470 // Here we use ReadMsg and WriteMsg to send messages with
471 // a header with size information. Also, the reception is
472 // event triggered, so we test input events as well.
474 // We need to set no flags here (ReadMsg and WriteMsg are
475 // not affected by flags)
477 m_sock
->SetFlags(wxSOCKET_WAITALL
);
479 wxString s
= wxGetTextFromUser(
480 _("Enter an arbitrary string to send to the server:"),
482 _("Yes I like wxWidgets!"));
484 const wxScopedCharBuffer
msg1(s
.utf8_str());
485 size_t len
= wxStrlen(msg1
) + 1;
486 wxCharBuffer
msg2(wxStrlen(msg1
));
488 m_text
->AppendText(_("Sending the string with WriteMsg ..."));
489 m_sock
->WriteMsg(msg1
, len
);
490 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
491 m_text
->AppendText(_("Waiting for an event (timeout = 2 sec)\n"));
493 // Wait until data available (will also return if the connection is lost)
494 m_sock
->WaitForRead(2);
496 if (m_sock
->IsData())
498 m_text
->AppendText(_("Reading the string back with ReadMsg ..."));
499 m_sock
->ReadMsg(msg2
.data(), len
);
500 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
501 m_text
->AppendText(_("Comparing the two buffers ..."));
502 if (memcmp(msg1
, msg2
, len
) != 0)
504 m_text
->AppendText(_("failed!\n"));
505 m_text
->AppendText(_("Test 2 failed !\n"));
509 m_text
->AppendText(_("done\n"));
510 m_text
->AppendText(_("Test 2 passed !\n"));
514 m_text
->AppendText(_("Timeout ! Test 2 failed.\n"));
516 m_text
->AppendText(_("=== Test 2 ends ===\n"));
522 void MyFrame::OnTest3(wxCommandEvent
& WXUNUSED(event
))
524 // Disable socket menu entries (exception: Close Session)
528 m_text
->AppendText(_("\n=== Test 3 begins ===\n"));
530 // Tell the server which test we are running
531 unsigned char c
= 0xDE;
532 m_sock
->Write(&c
, 1);
534 // This test also is similar to the first one but it sends a
535 // large buffer so that wxSocket is actually forced to split
536 // it into pieces and take care of sending everything before
539 m_sock
->SetFlags(wxSOCKET_WAITALL
);
541 // Note that len is in kbytes here!
542 const unsigned char len
= 32;
543 wxCharBuffer
buf1(len
* 1024),
546 for (size_t i
= 0; i
< len
* 1024; i
++)
547 buf1
.data()[i
] = (char)(i
% 256);
549 m_text
->AppendText(_("Sending a large buffer (32K) to the server ..."));
550 m_sock
->Write(&len
, 1);
551 m_sock
->Write(buf1
, len
* 1024);
552 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
554 m_text
->AppendText(_("Receiving the buffer back from server ..."));
555 m_sock
->Read(buf2
.data(), len
* 1024);
556 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
558 m_text
->AppendText(_("Comparing the two buffers ..."));
559 if (memcmp(buf1
, buf2
, len
) != 0)
561 m_text
->AppendText(_("failed!\n"));
562 m_text
->AppendText(_("Test 3 failed !\n"));
566 m_text
->AppendText(_("done\n"));
567 m_text
->AppendText(_("Test 3 passed !\n"));
569 m_text
->AppendText(_("=== Test 3 ends ===\n"));
575 void MyFrame::OnCloseConnection(wxCommandEvent
& WXUNUSED(event
))
581 void MyFrame::OnDatagram(wxCommandEvent
& WXUNUSED(event
))
583 wxString hostname
= wxGetTextFromUser
585 "Enter the address of the wxSocket demo server:",
589 if ( hostname
.empty() )
592 TestLogger
logtest("UDP");
594 wxIPV4address addrLocal
;
595 addrLocal
.Hostname();
596 wxDatagramSocket
sock(addrLocal
);
599 wxLogMessage("ERROR: failed to create UDP socket");
603 wxLogMessage("Created UDP socket at %s:%u",
604 addrLocal
.IPAddress(), addrLocal
.Service());
606 wxIPV4address addrPeer
;
607 addrPeer
.Hostname(hostname
);
608 addrPeer
.Service(3000);
610 wxLogMessage("Testing UDP with peer at %s:%u",
611 addrPeer
.IPAddress(), addrPeer
.Service());
613 char buf
[] = "Uryyb sebz pyvrag!";
614 if ( sock
.SendTo(addrPeer
, buf
, sizeof(buf
)).LastCount() != sizeof(buf
) )
616 wxLogMessage("ERROR: failed to send data");
620 if ( sock
.RecvFrom(addrPeer
, buf
, sizeof(buf
)).LastCount() != sizeof(buf
) )
622 wxLogMessage("ERROR: failed to receive data");
626 wxLogMessage("Received \"%s\" from %s:%u.",
627 wxString::From8BitData(buf
, sock
.LastCount()),
628 addrPeer
.IPAddress(), addrPeer
.Service());
633 void MyFrame::OnTestURL(wxCommandEvent
& WXUNUSED(event
))
636 static wxString
s_urlname("http://www.google.com/");
637 wxString urlname
= wxGetTextFromUser
639 _("Enter an URL to get"),
643 if ( urlname
.empty() )
644 return; // cancelled by user
649 TestLogger
logtest("URL");
653 if ( url
.GetError() != wxURL_NOERR
)
655 wxLogError("Failed to parse URL \"%s\"", urlname
);
659 // Try to get the input stream (connects to the given URL)
660 wxLogMessage("Establishing connection to \"%s\"...", urlname
);
661 const std::auto_ptr
<wxInputStream
> data(url
.GetInputStream());
664 wxLogError("Failed to retrieve URL \"%s\"", urlname
);
668 // Print the contents type and file size
669 wxLogMessage("Contents type: %s\nFile size: %i\nStarting to download...",
670 url
.GetProtocol().GetContentType(),
674 wxStringOutputStream sout
;
675 if ( data
->Read(sout
).GetLastError() != wxSTREAM_EOF
)
676 wxLogError("Error reading the input stream.");
678 wxLogMessage("Text retrieved from URL \"%s\" follows:\n%s",
679 urlname
, sout
.GetString());
684 void MyFrame::OnSocketEvent(wxSocketEvent
& event
)
686 wxString s
= _("OnSocketEvent: ");
688 switch(event
.GetSocketEvent())
690 case wxSOCKET_INPUT
: s
.Append(_("wxSOCKET_INPUT\n")); break;
691 case wxSOCKET_LOST
: s
.Append(_("wxSOCKET_LOST\n")); break;
692 case wxSOCKET_CONNECTION
: s
.Append(_("wxSOCKET_CONNECTION\n")); break;
693 default : s
.Append(_("Unexpected event !\n")); break;
696 m_text
->AppendText(s
);
700 // convenience functions
702 void MyFrame::UpdateStatusBar()
706 if (!m_sock
->IsConnected())
708 s
.Printf(_("Not connected"));
718 m_sock
->GetPeer(addr
);
719 s
.Printf(_("%s : %d"), (addr
.Hostname()).c_str(), addr
.Service());
724 #endif // wxUSE_STATUSBAR
726 m_menuSocket
->Enable(CLIENT_OPEN
, !m_sock
->IsConnected() && !m_busy
);
728 m_menuSocket
->Enable(CLIENT_OPENIPV6
, !m_sock
->IsConnected() && !m_busy
);
730 m_menuSocket
->Enable(CLIENT_TEST1
, m_sock
->IsConnected() && !m_busy
);
731 m_menuSocket
->Enable(CLIENT_TEST2
, m_sock
->IsConnected() && !m_busy
);
732 m_menuSocket
->Enable(CLIENT_TEST3
, m_sock
->IsConnected() && !m_busy
);
733 m_menuSocket
->Enable(CLIENT_CLOSE
, m_sock
->IsConnected());