]> git.saurik.com Git - wxWidgets.git/blob - samples/sockets/client.cpp
Simplify wxFileNameFromPath() implementation to avoid redundancy.
[wxWidgets.git] / samples / sockets / client.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: client.cpp
3 // Purpose: Client for wxSocket demo
4 // Author: Guillermo Rodriguez Garcia <guille@iies.es>
5 // Modified by:
6 // Created: 1999/09/19
7 // RCS-ID: $Id$
8 // Copyright: (c) 1999 Guillermo Rodriguez Garcia
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ==========================================================================
13 // declarations
14 // ==========================================================================
15
16 // --------------------------------------------------------------------------
17 // headers
18 // --------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx/wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 # pragma hdrstop
25 #endif
26
27 // for all others, include the necessary headers
28 #ifndef WX_PRECOMP
29 # include "wx/wx.h"
30 #endif
31
32 #include "wx/socket.h"
33 #include "wx/url.h"
34 #include "wx/sstream.h"
35 #include <memory>
36
37 // --------------------------------------------------------------------------
38 // resources
39 // --------------------------------------------------------------------------
40
41 // the application icon
42 #if !defined(__WXMSW__) && !defined(__WXPM__)
43 #include "../sample.xpm"
44 #endif
45
46 // --------------------------------------------------------------------------
47 // classes
48 // --------------------------------------------------------------------------
49
50 // Define a new application type
51 class MyApp : public wxApp
52 {
53 public:
54 virtual bool OnInit();
55 };
56
57 // Define a new frame type: this is going to be our main frame
58 class MyFrame : public wxFrame
59 {
60 public:
61 MyFrame();
62 ~MyFrame();
63
64 // event handlers for File menu
65 void OnQuit(wxCommandEvent& event);
66 void OnAbout(wxCommandEvent& event);
67
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);
74
75 #if wxUSE_URL
76 // event handlers for Protocols menu
77 void OnTestURL(wxCommandEvent& event);
78 #endif
79 #if wxUSE_IPV6
80 void OnOpenConnectionIPv6(wxCommandEvent& event);
81 #endif
82
83 void OpenConnection(wxSockAddress::Family family);
84
85 // event handlers for DatagramSocket menu (stub)
86 void OnDatagram(wxCommandEvent& event);
87
88 // socket event handler
89 void OnSocketEvent(wxSocketEvent& event);
90
91 // convenience functions
92 void UpdateStatusBar();
93
94 private:
95 wxSocketClient *m_sock;
96 wxTextCtrl *m_text;
97 wxMenu *m_menuFile;
98 wxMenu *m_menuSocket;
99 wxMenu *m_menuDatagramSocket;
100 wxMenu *m_menuProtocols;
101 wxMenuBar *m_menuBar;
102 bool m_busy;
103
104 // any class wishing to process wxWidgets events must use this macro
105 DECLARE_EVENT_TABLE()
106 };
107
108 // simple helper class to log start and end of each test
109 class TestLogger
110 {
111 public:
112 TestLogger(const wxString& name) : m_name(name)
113 {
114 wxLogMessage("=== %s test begins ===", m_name);
115 }
116
117 ~TestLogger()
118 {
119 wxLogMessage("=== %s test ends ===", m_name);
120 }
121
122 private:
123 const wxString m_name;
124 };
125
126 // --------------------------------------------------------------------------
127 // constants
128 // --------------------------------------------------------------------------
129
130 // IDs for the controls and the menu commands
131 enum
132 {
133 // menu items
134 CLIENT_QUIT = wxID_EXIT,
135 CLIENT_ABOUT = wxID_ABOUT,
136 CLIENT_OPEN = 100,
137 #if wxUSE_IPV6
138 CLIENT_OPENIPV6,
139 #endif
140 CLIENT_TEST1,
141 CLIENT_TEST2,
142 CLIENT_TEST3,
143 CLIENT_CLOSE,
144 #if wxUSE_URL
145 CLIENT_TESTURL,
146 #endif
147 CLIENT_DGRAM,
148
149 // id for socket
150 SOCKET_ID
151 };
152
153 // --------------------------------------------------------------------------
154 // event tables and other macros for wxWidgets
155 // --------------------------------------------------------------------------
156
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)
161 #if wxUSE_IPV6
162 EVT_MENU(CLIENT_OPENIPV6, MyFrame::OnOpenConnectionIPv6)
163 #endif
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)
169 #if wxUSE_URL
170 EVT_MENU(CLIENT_TESTURL, MyFrame::OnTestURL)
171 #endif
172 EVT_SOCKET(SOCKET_ID, MyFrame::OnSocketEvent)
173 END_EVENT_TABLE()
174
175 IMPLEMENT_APP(MyApp)
176
177 // ==========================================================================
178 // implementation
179 // ==========================================================================
180
181 // --------------------------------------------------------------------------
182 // the application class
183 // --------------------------------------------------------------------------
184
185 bool MyApp::OnInit()
186 {
187 if ( !wxApp::OnInit() )
188 return false;
189
190 // Create the main application window
191 MyFrame *frame = new MyFrame();
192
193 // Show it and tell the application that it's our main window
194 frame->Show(true);
195 SetTopWindow(frame);
196
197 // success
198 return true;
199 }
200
201 // --------------------------------------------------------------------------
202 // main frame
203 // --------------------------------------------------------------------------
204
205 // frame constructor
206 MyFrame::MyFrame() : wxFrame((wxFrame *)NULL, wxID_ANY,
207 _("wxSocket demo: Client"),
208 wxDefaultPosition, wxSize(300, 200))
209 {
210 // Give the frame an icon
211 SetIcon(wxICON(sample));
212
213 // Make menus
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"));
218
219 m_menuSocket = new wxMenu();
220 m_menuSocket->Append(CLIENT_OPEN, _("&Open session\tCtrl-O"), _("Connect to server"));
221 #if wxUSE_IPV6
222 m_menuSocket->Append(CLIENT_OPENIPV6, _("&Open session(IPv6)\tShift-Ctrl-O"), _("Connect to server(IPv6)"));
223 #endif
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"));
230
231 m_menuDatagramSocket = new wxMenu();
232 m_menuDatagramSocket->Append(CLIENT_DGRAM, _("&Datagram test\tCtrl-D"), _("Test UDP sockets"));
233
234 #if wxUSE_URL
235 m_menuProtocols = new wxMenu();
236 m_menuProtocols->Append(CLIENT_TESTURL, _("Test URL\tCtrl-U"),
237 _("Get data from the specified URL"));
238 #endif
239
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"));
245 #if wxUSE_URL
246 m_menuBar->Append(m_menuProtocols, _("&Protocols"));
247 #endif
248 SetMenuBar(m_menuBar);
249
250 #if wxUSE_STATUSBAR
251 // Status bar
252 CreateStatusBar(2);
253 #endif // wxUSE_STATUSBAR
254
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));
261
262 // Create the socket
263 m_sock = new wxSocketClient();
264
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 |
269 wxSOCKET_LOST_FLAG);
270 m_sock->Notify(true);
271
272 m_busy = false;
273 UpdateStatusBar();
274 }
275
276 MyFrame::~MyFrame()
277 {
278 // No delayed deletion here, as the frame is dying anyway
279 delete m_sock;
280 }
281
282 // event handlers
283
284 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
285 {
286 // true is to force the frame to close
287 Close(true);
288 }
289
290 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
291 {
292 wxMessageBox(_("wxSocket demo: Client\n(c) 1999 Guillermo Rodriguez Garcia\n"),
293 _("About Client"),
294 wxOK | wxICON_INFORMATION, this);
295 }
296
297 void MyFrame::OnOpenConnection(wxCommandEvent& WXUNUSED(event))
298 {
299 OpenConnection(wxSockAddress::IPV4);
300 }
301 #if wxUSE_IPV6
302 void MyFrame::OnOpenConnectionIPv6(wxCommandEvent& WXUNUSED(event))
303 {
304 OpenConnection(wxSockAddress::IPV6);
305 }
306 #endif // wxUSE_IPV6
307
308 void MyFrame::OpenConnection(wxSockAddress::Family family)
309 {
310 wxUnusedVar(family); // unused in !wxUSE_IPV6 case
311
312 wxIPaddress * addr;
313 wxIPV4address addr4;
314 #if wxUSE_IPV6
315 wxIPV6address addr6;
316 if ( family == wxSockAddress::IPV6 )
317 addr = &addr6;
318 else
319 #endif
320 addr = &addr4;
321
322 m_menuSocket->Enable(CLIENT_OPEN, false);
323 #if wxUSE_IPV6
324 m_menuSocket->Enable(CLIENT_OPENIPV6, false);
325 #endif
326 m_menuSocket->Enable(CLIENT_CLOSE, false);
327
328 // Ask user for server address
329 wxString hostname = wxGetTextFromUser(
330 _("Enter the address of the wxSocket demo server:"),
331 _("Connect ..."),
332 _("localhost"));
333 if ( hostname.empty() )
334 return;
335
336 addr->Hostname(hostname);
337 addr->Service(3000);
338
339 // we connect asynchronously and will get a wxSOCKET_CONNECTION event when
340 // the connection is really established
341 //
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());
345
346 m_sock->Connect(*addr, false);
347 }
348
349 void MyFrame::OnTest1(wxCommandEvent& WXUNUSED(event))
350 {
351 // Disable socket menu entries (exception: Close Session)
352 m_busy = true;
353 UpdateStatusBar();
354
355 m_text->AppendText(_("\n=== Test 1 begins ===\n"));
356
357 // Tell the server which test we are running
358 unsigned char c = 0xBE;
359 m_sock->Write(&c, 1);
360
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.
366 //
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?)
372
373 m_sock->SetFlags(wxSOCKET_WAITALL);
374
375 const char *buf1 = "Test string (less than 256 chars!)";
376 unsigned char len = (unsigned char)(wxStrlen(buf1) + 1);
377 wxCharBuffer buf2(wxStrlen(buf1));
378
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"));
383
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"));
387
388 m_text->AppendText(_("Comparing the two buffers ..."));
389 if (memcmp(buf1, buf2, len) != 0)
390 {
391 m_text->AppendText(_("failed!\n"));
392 m_text->AppendText(_("Test 1 failed !\n"));
393 }
394 else
395 {
396 m_text->AppendText(_("done\n"));
397 m_text->AppendText(_("Test 1 passed !\n"));
398 }
399 m_text->AppendText(_("=== Test 1 ends ===\n"));
400
401 m_busy = false;
402 UpdateStatusBar();
403 }
404
405 void MyFrame::OnTest2(wxCommandEvent& WXUNUSED(event))
406 {
407 // Disable socket menu entries (exception: Close Session)
408 m_busy = true;
409 UpdateStatusBar();
410
411 m_text->AppendText(_("\n=== Test 2 begins ===\n"));
412
413 // Tell the server which test we are running
414 unsigned char c = 0xCE;
415 m_sock->Write(&c, 1);
416
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.
420 //
421 // We need to set no flags here (ReadMsg and WriteMsg are
422 // not affected by flags)
423
424 m_sock->SetFlags(wxSOCKET_WAITALL);
425
426 wxString s = wxGetTextFromUser(
427 _("Enter an arbitrary string to send to the server:"),
428 _("Test 2 ..."),
429 _("Yes I like wxWidgets!"));
430
431 const wxScopedCharBuffer msg1(s.utf8_str());
432 size_t len = wxStrlen(msg1) + 1;
433 wxCharBuffer msg2(wxStrlen(msg1));
434
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"));
439
440 // Wait until data available (will also return if the connection is lost)
441 m_sock->WaitForRead(2);
442
443 if (m_sock->IsData())
444 {
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)
450 {
451 m_text->AppendText(_("failed!\n"));
452 m_text->AppendText(_("Test 2 failed !\n"));
453 }
454 else
455 {
456 m_text->AppendText(_("done\n"));
457 m_text->AppendText(_("Test 2 passed !\n"));
458 }
459 }
460 else
461 m_text->AppendText(_("Timeout ! Test 2 failed.\n"));
462
463 m_text->AppendText(_("=== Test 2 ends ===\n"));
464
465 m_busy = false;
466 UpdateStatusBar();
467 }
468
469 void MyFrame::OnTest3(wxCommandEvent& WXUNUSED(event))
470 {
471 // Disable socket menu entries (exception: Close Session)
472 m_busy = true;
473 UpdateStatusBar();
474
475 m_text->AppendText(_("\n=== Test 3 begins ===\n"));
476
477 // Tell the server which test we are running
478 unsigned char c = 0xDE;
479 m_sock->Write(&c, 1);
480
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
484 // returning.
485
486 m_sock->SetFlags(wxSOCKET_WAITALL);
487
488 // Note that len is in kbytes here!
489 const unsigned char len = 32;
490 wxCharBuffer buf1(len * 1024),
491 buf2(len * 1024);
492
493 for (size_t i = 0; i < len * 1024; i ++)
494 buf1.data()[i] = (char)(i % 256);
495
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"));
500
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"));
504
505 m_text->AppendText(_("Comparing the two buffers ..."));
506 if (memcmp(buf1, buf2, len) != 0)
507 {
508 m_text->AppendText(_("failed!\n"));
509 m_text->AppendText(_("Test 3 failed !\n"));
510 }
511 else
512 {
513 m_text->AppendText(_("done\n"));
514 m_text->AppendText(_("Test 3 passed !\n"));
515 }
516 m_text->AppendText(_("=== Test 3 ends ===\n"));
517
518 m_busy = false;
519 UpdateStatusBar();
520 }
521
522 void MyFrame::OnCloseConnection(wxCommandEvent& WXUNUSED(event))
523 {
524 m_sock->Close();
525 UpdateStatusBar();
526 }
527
528 void MyFrame::OnDatagram(wxCommandEvent& WXUNUSED(event))
529 {
530 wxString hostname = wxGetTextFromUser
531 (
532 "Enter the address of the wxSocket demo server:",
533 "UDP peer",
534 "localhost"
535 );
536 if ( hostname.empty() )
537 return;
538
539 TestLogger logtest("UDP");
540
541 wxIPV4address addrLocal;
542 addrLocal.Hostname();
543 wxDatagramSocket sock(addrLocal);
544 if ( !sock.IsOk() )
545 {
546 wxLogMessage("ERROR: failed to create UDP socket");
547 return;
548 }
549
550 wxLogMessage("Created UDP socket at %s:%u",
551 addrLocal.IPAddress(), addrLocal.Service());
552
553 wxIPV4address addrPeer;
554 addrPeer.Hostname(hostname);
555 addrPeer.Service(3000);
556
557 wxLogMessage("Testing UDP with peer at %s:%u",
558 addrPeer.IPAddress(), addrPeer.Service());
559
560 char buf[] = "Uryyb sebz pyvrag!";
561 if ( sock.SendTo(addrPeer, buf, sizeof(buf)).LastCount() != sizeof(buf) )
562 {
563 wxLogMessage("ERROR: failed to send data");
564 return;
565 }
566
567 if ( sock.RecvFrom(addrPeer, buf, sizeof(buf)).LastCount() != sizeof(buf) )
568 {
569 wxLogMessage("ERROR: failed to receive data");
570 return;
571 }
572
573 wxLogMessage("Received \"%s\" from %s:%u.",
574 wxString::From8BitData(buf, sock.LastCount()),
575 addrPeer.IPAddress(), addrPeer.Service());
576 }
577
578 #if wxUSE_URL
579
580 void MyFrame::OnTestURL(wxCommandEvent& WXUNUSED(event))
581 {
582 // Ask for the URL
583 static wxString s_urlname("http://www.google.com/");
584 wxString urlname = wxGetTextFromUser
585 (
586 _("Enter an URL to get"),
587 _("URL:"),
588 s_urlname
589 );
590 if ( urlname.empty() )
591 return; // cancelled by user
592
593 s_urlname = urlname;
594
595
596 TestLogger logtest("URL");
597
598 // Parse the URL
599 wxURL url(urlname);
600 if ( url.GetError() != wxURL_NOERR )
601 {
602 wxLogError("Failed to parse URL \"%s\"", urlname);
603 return;
604 }
605
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());
609 if ( !data.get() )
610 {
611 wxLogError("Failed to retrieve URL \"%s\"", urlname);
612 return;
613 }
614
615 // Print the contents type and file size
616 wxLogMessage("Contents type: %s\nFile size: %i\nStarting to download...",
617 url.GetProtocol().GetContentType(),
618 data->GetSize());
619
620 // Get the data
621 wxStringOutputStream sout;
622 if ( data->Read(sout).GetLastError() != wxSTREAM_EOF )
623 {
624 wxLogError("Error reading the input stream.");
625 }
626
627 wxLogMessage("Text retrieved from URL \"%s\" follows:\n%s",
628 urlname, sout.GetString());
629 }
630
631 #endif // wxUSE_URL
632
633 void MyFrame::OnSocketEvent(wxSocketEvent& event)
634 {
635 switch ( event.GetSocketEvent() )
636 {
637 case wxSOCKET_INPUT:
638 wxLogMessage("Input available on the socket");
639 break;
640
641 case wxSOCKET_LOST:
642 wxLogMessage("Socket connection was unexpectedly lost.");
643 UpdateStatusBar();
644 break;
645
646 case wxSOCKET_CONNECTION:
647 wxLogMessage("... socket is now connected.");
648 UpdateStatusBar();
649 break;
650
651 default:
652 wxLogMessage("Unknown socket event!!!");
653 break;
654 }
655 }
656
657 // convenience functions
658
659 void MyFrame::UpdateStatusBar()
660 {
661 #if wxUSE_STATUSBAR
662 wxString s;
663
664 if (!m_sock->IsConnected())
665 {
666 s = "Not connected";
667 }
668 else
669 {
670 #if wxUSE_IPV6
671 wxIPV6address addr;
672 #else
673 wxIPV4address addr;
674 #endif
675
676 m_sock->GetPeer(addr);
677 s.Printf("%s : %d", addr.Hostname(), addr.Service());
678 }
679
680 SetStatusText(s, 1);
681 #endif // wxUSE_STATUSBAR
682
683 m_menuSocket->Enable(CLIENT_OPEN, !m_sock->IsConnected() && !m_busy);
684 #if wxUSE_IPV6
685 m_menuSocket->Enable(CLIENT_OPENIPV6, !m_sock->IsConnected() && !m_busy);
686 #endif
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());
691 }