]> git.saurik.com Git - wxWidgets.git/blob - samples/sockets/client.cpp
Assert correction.
[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 #if defined(__GNUG__) && !defined(__APPLE__)
21 #pragma implementation
22 #pragma interface
23 #endif
24
25 // For compilers that support precompilation, includes "wx/wx.h".
26 #include "wx/wxprec.h"
27
28 #ifdef __BORLANDC__
29 # pragma hdrstop
30 #endif
31
32 // for all others, include the necessary headers
33 #ifndef WX_PRECOMP
34 # include "wx/wx.h"
35 #endif
36
37 #include "wx/socket.h"
38 #include "wx/url.h"
39 #include "wx/wfstream.h"
40
41 // --------------------------------------------------------------------------
42 // resources
43 // --------------------------------------------------------------------------
44
45 // the application icon
46 #if defined(__WXGTK__) || defined(__WXX11__) || defined(__WXMOTIF__) || defined(__WXMAC__)
47 # include "mondrian.xpm"
48 #endif
49
50 // --------------------------------------------------------------------------
51 // classes
52 // --------------------------------------------------------------------------
53
54 // Define a new application type
55 class MyApp : public wxApp
56 {
57 public:
58 virtual bool OnInit();
59 };
60
61 // Define a new frame type: this is going to be our main frame
62 class MyFrame : public wxFrame
63 {
64 public:
65 MyFrame();
66 ~MyFrame();
67
68 // event handlers for File menu
69 void OnQuit(wxCommandEvent& event);
70 void OnAbout(wxCommandEvent& event);
71
72 // event handlers for Socket menu
73 void OnOpenConnection(wxCommandEvent& event);
74 void OnTest1(wxCommandEvent& event);
75 void OnTest2(wxCommandEvent& event);
76 void OnTest3(wxCommandEvent& event);
77 void OnCloseConnection(wxCommandEvent& event);
78
79 #if wxUSE_URL
80 // event handlers for Protocols menu
81 void OnTestURL(wxCommandEvent& event);
82 #endif
83
84 // event handlers for DatagramSocket menu (stub)
85 void OnDatagram(wxCommandEvent& event);
86
87 // socket event handler
88 void OnSocketEvent(wxSocketEvent& event);
89
90 // convenience functions
91 void UpdateStatusBar();
92
93 private:
94 wxSocketClient *m_sock;
95 wxTextCtrl *m_text;
96 wxMenu *m_menuFile;
97 wxMenu *m_menuSocket;
98 wxMenu *m_menuDatagramSocket;
99 wxMenu *m_menuProtocols;
100 wxMenuBar *m_menuBar;
101 bool m_busy;
102
103 // any class wishing to process wxWidgets events must use this macro
104 DECLARE_EVENT_TABLE()
105 };
106
107 // --------------------------------------------------------------------------
108 // constants
109 // --------------------------------------------------------------------------
110
111 // IDs for the controls and the menu commands
112 enum
113 {
114 // menu items
115 CLIENT_QUIT = wxID_EXIT,
116 CLIENT_ABOUT = wxID_ABOUT,
117 CLIENT_OPEN = 100,
118 CLIENT_TEST1,
119 CLIENT_TEST2,
120 CLIENT_TEST3,
121 CLIENT_CLOSE,
122 #if wxUSE_URL
123 CLIENT_TESTURL,
124 #endif
125 CLIENT_DGRAM,
126
127 // id for socket
128 SOCKET_ID
129 };
130
131 // --------------------------------------------------------------------------
132 // event tables and other macros for wxWidgets
133 // --------------------------------------------------------------------------
134
135 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
136 EVT_MENU(CLIENT_QUIT, MyFrame::OnQuit)
137 EVT_MENU(CLIENT_ABOUT, MyFrame::OnAbout)
138 EVT_MENU(CLIENT_OPEN, MyFrame::OnOpenConnection)
139 EVT_MENU(CLIENT_TEST1, MyFrame::OnTest1)
140 EVT_MENU(CLIENT_TEST2, MyFrame::OnTest2)
141 EVT_MENU(CLIENT_TEST3, MyFrame::OnTest3)
142 EVT_MENU(CLIENT_CLOSE, MyFrame::OnCloseConnection)
143 EVT_MENU(CLIENT_DGRAM, MyFrame::OnDatagram)
144 #if wxUSE_URL
145 EVT_MENU(CLIENT_TESTURL, MyFrame::OnTestURL)
146 #endif
147 EVT_SOCKET(SOCKET_ID, MyFrame::OnSocketEvent)
148 END_EVENT_TABLE()
149
150 IMPLEMENT_APP(MyApp)
151
152 // ==========================================================================
153 // implementation
154 // ==========================================================================
155
156 // --------------------------------------------------------------------------
157 // the application class
158 // --------------------------------------------------------------------------
159
160 bool MyApp::OnInit()
161 {
162 // Create the main application window
163 MyFrame *frame = new MyFrame();
164
165 // Show it and tell the application that it's our main window
166 frame->Show(true);
167 SetTopWindow(frame);
168
169 // success
170 return true;
171 }
172
173 // --------------------------------------------------------------------------
174 // main frame
175 // --------------------------------------------------------------------------
176
177 // frame constructor
178 MyFrame::MyFrame() : wxFrame((wxFrame *)NULL, wxID_ANY,
179 _("wxSocket demo: Client"),
180 wxDefaultPosition, wxSize(300, 200))
181 {
182 // Give the frame an icon
183 SetIcon(wxICON(mondrian));
184
185 // Make menus
186 m_menuFile = new wxMenu();
187 m_menuFile->Append(CLIENT_ABOUT, _("&About...\tCtrl-A"), _("Show about dialog"));
188 m_menuFile->AppendSeparator();
189 m_menuFile->Append(CLIENT_QUIT, _("E&xit\tAlt-X"), _("Quit client"));
190
191 m_menuSocket = new wxMenu();
192 m_menuSocket->Append(CLIENT_OPEN, _("&Open session"), _("Connect to server"));
193 m_menuSocket->AppendSeparator();
194 m_menuSocket->Append(CLIENT_TEST1, _("Test &1"), _("Test basic functionality"));
195 m_menuSocket->Append(CLIENT_TEST2, _("Test &2"), _("Test ReadMsg and WriteMsg"));
196 m_menuSocket->Append(CLIENT_TEST3, _("Test &3"), _("Test large data transfer"));
197 m_menuSocket->AppendSeparator();
198 m_menuSocket->Append(CLIENT_CLOSE, _("&Close session"), _("Close connection"));
199
200 m_menuDatagramSocket = new wxMenu();
201 m_menuDatagramSocket->Append(CLIENT_DGRAM, _("Send Datagram"), _("Test UDP sockets"));
202
203 #if wxUSE_URL
204 m_menuProtocols = new wxMenu();
205 m_menuProtocols->Append(CLIENT_TESTURL, _("Test URL"), _("Get data from the specified URL"));
206 #endif
207
208 // Append menus to the menubar
209 m_menuBar = new wxMenuBar();
210 m_menuBar->Append(m_menuFile, _("&File"));
211 m_menuBar->Append(m_menuSocket, _("&SocketClient"));
212 m_menuBar->Append(m_menuDatagramSocket, _("&DatagramSocket"));
213 #if wxUSE_URL
214 m_menuBar->Append(m_menuProtocols, _("&Protocols"));
215 #endif
216 SetMenuBar(m_menuBar);
217
218 #if wxUSE_STATUSBAR
219 // Status bar
220 CreateStatusBar(2);
221 #endif // wxUSE_STATUSBAR
222
223 // Make a textctrl for logging
224 m_text = new wxTextCtrl(this, wxID_ANY,
225 _("Welcome to wxSocket demo: Client\nClient ready\n"),
226 wxDefaultPosition, wxDefaultSize,
227 wxTE_MULTILINE | wxTE_READONLY);
228
229 // Create the socket
230 m_sock = new wxSocketClient();
231
232 // Setup the event handler and subscribe to most events
233 m_sock->SetEventHandler(*this, SOCKET_ID);
234 m_sock->SetNotify(wxSOCKET_CONNECTION_FLAG |
235 wxSOCKET_INPUT_FLAG |
236 wxSOCKET_LOST_FLAG);
237 m_sock->Notify(true);
238
239 m_busy = false;
240 UpdateStatusBar();
241 }
242
243 MyFrame::~MyFrame()
244 {
245 // No delayed deletion here, as the frame is dying anyway
246 delete m_sock;
247 }
248
249 // event handlers
250
251 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
252 {
253 // true is to force the frame to close
254 Close(true);
255 }
256
257 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
258 {
259 wxMessageBox(_("wxSocket demo: Client\n(c) 1999 Guillermo Rodriguez Garcia\n"),
260 _("About Client"),
261 wxOK | wxICON_INFORMATION, this);
262 }
263
264 void MyFrame::OnOpenConnection(wxCommandEvent& WXUNUSED(event))
265 {
266 wxIPV4address addr;
267
268 m_menuSocket->Enable(CLIENT_OPEN, false);
269 m_menuSocket->Enable(CLIENT_CLOSE, false);
270
271 // Ask user for server address
272 wxString hostname = wxGetTextFromUser(
273 _("Enter the address of the wxSocket demo server:"),
274 _("Connect ..."),
275 _("localhost"));
276
277 addr.Hostname(hostname);
278 addr.Service(3000);
279
280 // Mini-tutorial for Connect() :-)
281 // ---------------------------
282 //
283 // There are two ways to use Connect(): blocking and non-blocking,
284 // depending on the value passed as the 'wait' (2nd) parameter.
285 //
286 // Connect(addr, true) will wait until the connection completes,
287 // returning true on success and false on failure. This call blocks
288 // the GUI (this might be changed in future releases to honour the
289 // wxSOCKET_BLOCK flag).
290 //
291 // Connect(addr, false) will issue a nonblocking connection request
292 // and return immediately. If the return value is true, then the
293 // connection has been already successfully established. If it is
294 // false, you must wait for the request to complete, either with
295 // WaitOnConnect() or by watching wxSOCKET_CONNECTION / LOST
296 // events (please read the documentation).
297 //
298 // WaitOnConnect() itself never blocks the GUI (this might change
299 // in the future to honour the wxSOCKET_BLOCK flag). This call will
300 // return false on timeout, or true if the connection request
301 // completes, which in turn might mean:
302 //
303 // a) That the connection was successfully established
304 // b) That the connection request failed (for example, because
305 // it was refused by the peer.
306 //
307 // Use IsConnected() to distinguish between these two.
308 //
309 // So, in a brief, you should do one of the following things:
310 //
311 // For blocking Connect:
312 //
313 // bool success = client->Connect(addr, true);
314 //
315 // For nonblocking Connect:
316 //
317 // client->Connect(addr, false);
318 //
319 // bool waitmore = true;
320 // while (! client->WaitOnConnect(seconds, millis) && waitmore )
321 // {
322 // // possibly give some feedback to the user,
323 // // update waitmore if needed.
324 // }
325 // bool success = client->IsConnected();
326 //
327 // And that's all :-)
328
329 m_text->AppendText(_("\nTrying to connect (timeout = 10 sec) ...\n"));
330 m_sock->Connect(addr, false);
331 m_sock->WaitOnConnect(10);
332
333 if (m_sock->IsConnected())
334 m_text->AppendText(_("Succeeded ! Connection established\n"));
335 else
336 {
337 m_sock->Close();
338 m_text->AppendText(_("Failed ! Unable to connect\n"));
339 wxMessageBox(_("Can't connect to the specified host"), _("Alert !"));
340 }
341
342 UpdateStatusBar();
343 }
344
345 void MyFrame::OnTest1(wxCommandEvent& WXUNUSED(event))
346 {
347 const wxChar *buf1;
348 wxChar *buf2;
349 unsigned char len;
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 buf1 = _("Test string (less than 256 chars!)");
376 len = (unsigned char)((wxStrlen(buf1) + 1) * sizeof(wxChar));
377 buf2 = new wxChar[wxStrlen(buf1) + 1];
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, 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 delete[] buf2;
402 m_busy = false;
403 UpdateStatusBar();
404 }
405
406 void MyFrame::OnTest2(wxCommandEvent& WXUNUSED(event))
407 {
408 const wxChar *msg1;
409 wxChar *msg2;
410 size_t len;
411
412 // Disable socket menu entries (exception: Close Session)
413 m_busy = true;
414 UpdateStatusBar();
415
416 m_text->AppendText(_("\n=== Test 2 begins ===\n"));
417
418 // Tell the server which test we are running
419 unsigned char c = 0xCE;
420 m_sock->Write(&c, 1);
421
422 // Here we use ReadMsg and WriteMsg to send messages with
423 // a header with size information. Also, the reception is
424 // event triggered, so we test input events as well.
425 //
426 // We need to set no flags here (ReadMsg and WriteMsg are
427 // not affected by flags)
428
429 m_sock->SetFlags(wxSOCKET_WAITALL);
430
431 wxString s = wxGetTextFromUser(
432 _("Enter an arbitrary string to send to the server:"),
433 _("Test 2 ..."),
434 _("Yes I like wxWidgets!"));
435
436 msg1 = s.c_str();
437 len = (wxStrlen(msg1) + 1) * sizeof(wxChar);
438 msg2 = new wxChar[wxStrlen(msg1) + 1];
439
440 m_text->AppendText(_("Sending the string with WriteMsg ..."));
441 m_sock->WriteMsg(msg1, len);
442 m_text->AppendText(m_sock->Error() ? _("failed !\n") : _("done\n"));
443 m_text->AppendText(_("Waiting for an event (timeout = 2 sec)\n"));
444
445 // Wait until data available (will also return if the connection is lost)
446 m_sock->WaitForRead(2);
447
448 if (m_sock->IsData())
449 {
450 m_text->AppendText(_("Reading the string back with ReadMsg ..."));
451 m_sock->ReadMsg(msg2, len);
452 m_text->AppendText(m_sock->Error() ? _("failed !\n") : _("done\n"));
453 m_text->AppendText(_("Comparing the two buffers ..."));
454 if (memcmp(msg1, msg2, len) != 0)
455 {
456 m_text->AppendText(_("failed!\n"));
457 m_text->AppendText(_("Test 2 failed !\n"));
458 }
459 else
460 {
461 m_text->AppendText(_("done\n"));
462 m_text->AppendText(_("Test 2 passed !\n"));
463 }
464 }
465 else
466 m_text->AppendText(_("Timeout ! Test 2 failed.\n"));
467
468 m_text->AppendText(_("=== Test 2 ends ===\n"));
469
470 delete[] msg2;
471 m_busy = false;
472 UpdateStatusBar();
473 }
474
475 void MyFrame::OnTest3(wxCommandEvent& WXUNUSED(event))
476 {
477 char *buf1;
478 char *buf2;
479 unsigned char len;
480
481 // Disable socket menu entries (exception: Close Session)
482 m_busy = true;
483 UpdateStatusBar();
484
485 m_text->AppendText(_("\n=== Test 3 begins ===\n"));
486
487 // Tell the server which test we are running
488 unsigned char c = 0xDE;
489 m_sock->Write(&c, 1);
490
491 // This test also is similar to the first one but it sends a
492 // large buffer so that wxSocket is actually forced to split
493 // it into pieces and take care of sending everything before
494 // returning.
495
496 m_sock->SetFlags(wxSOCKET_WAITALL);
497
498 // Note that len is in kbytes here!
499 len = 32;
500 buf1 = new char[len * 1024];
501 buf2 = new char[len * 1024];
502
503 for (int i = 0; i < len * 1024; i ++)
504 buf1[i] = (char)(i % 256);
505
506 m_text->AppendText(_("Sending a large buffer (32K) to the server ..."));
507 m_sock->Write(&len, 1);
508 m_sock->Write(buf1, len * 1024);
509 m_text->AppendText(m_sock->Error() ? _("failed !\n") : _("done\n"));
510
511 m_text->AppendText(_("Receiving the buffer back from server ..."));
512 m_sock->Read(buf2, len * 1024);
513 m_text->AppendText(m_sock->Error() ? _("failed !\n") : _("done\n"));
514
515 m_text->AppendText(_("Comparing the two buffers ..."));
516 if (memcmp(buf1, buf2, len) != 0)
517 {
518 m_text->AppendText(_("failed!\n"));
519 m_text->AppendText(_("Test 3 failed !\n"));
520 }
521 else
522 {
523 m_text->AppendText(_("done\n"));
524 m_text->AppendText(_("Test 3 passed !\n"));
525 }
526 m_text->AppendText(_("=== Test 3 ends ===\n"));
527
528 delete[] buf2;
529 m_busy = false;
530 UpdateStatusBar();
531 }
532
533 void MyFrame::OnCloseConnection(wxCommandEvent& WXUNUSED(event))
534 {
535 m_sock->Close();
536 UpdateStatusBar();
537 }
538
539 void MyFrame::OnDatagram(wxCommandEvent& WXUNUSED(event))
540 {
541 m_text->AppendText(_("\n=== Datagram test begins ===\n"));
542 m_text->AppendText(_("Sorry, not implemented\n"));
543 m_text->AppendText(_("=== Datagram test ends ===\n"));
544 }
545
546 #if wxUSE_URL
547
548 void MyFrame::OnTestURL(wxCommandEvent& WXUNUSED(event))
549 {
550 // Note that we are creating a new socket here, so this
551 // won't mess with the client/server demo.
552
553 // Ask for the URL
554 m_text->AppendText(_("\n=== URL test begins ===\n"));
555 wxString urlname = wxGetTextFromUser(_("Enter an URL to get"),
556 _("URL:"),
557 _T("http://localhost"));
558
559 // Parse the URL
560 wxURL url(urlname);
561 if (url.GetError() != wxURL_NOERR)
562 {
563 m_text->AppendText(_("Error: couldn't parse URL\n"));
564 m_text->AppendText(_("=== URL test ends ===\n"));
565 return;
566 }
567
568 // Try to get the input stream (connects to the given URL)
569 m_text->AppendText(_("Trying to establish connection...\n"));
570 wxYield();
571 wxInputStream *data = url.GetInputStream();
572 if (!data)
573 {
574 m_text->AppendText(_("Error: couldn't read from URL\n"));
575 m_text->AppendText(_("=== URL test ends ===\n"));
576 return;
577 }
578
579 // Print the contents type and file size
580 wxString s;
581 s.Printf(_("Contents type: %s\nFile size: %i\nStarting to download...\n"),
582 url.GetProtocol().GetContentType().c_str(),
583 data->GetSize());
584 m_text->AppendText(s);
585 wxYield();
586
587 // Get the data
588 wxFile fileTest(wxT("test.url"), wxFile::write);
589 wxFileOutputStream sout(fileTest);
590 if (!sout.Ok())
591 {
592 m_text->AppendText(_("Error: couldn't open file for output\n"));
593 m_text->AppendText(_("=== URL test ends ===\n"));
594 return;
595 }
596
597 data->Read(sout);
598 m_text->AppendText(_("Results written to file: test.url\n"));
599 m_text->AppendText(_("Done.\n"));
600 m_text->AppendText(_("=== URL test ends ===\n"));
601
602 delete data;
603 }
604
605 #endif
606
607 void MyFrame::OnSocketEvent(wxSocketEvent& event)
608 {
609 wxString s = _("OnSocketEvent: ");
610
611 switch(event.GetSocketEvent())
612 {
613 case wxSOCKET_INPUT : s.Append(_("wxSOCKET_INPUT\n")); break;
614 case wxSOCKET_LOST : s.Append(_("wxSOCKET_LOST\n")); break;
615 case wxSOCKET_CONNECTION : s.Append(_("wxSOCKET_CONNECTION\n")); break;
616 default : s.Append(_("Unexpected event !\n")); break;
617 }
618
619 m_text->AppendText(s);
620 UpdateStatusBar();
621 }
622
623 // convenience functions
624
625 void MyFrame::UpdateStatusBar()
626 {
627 wxString s;
628
629 if (!m_sock->IsConnected())
630 {
631 s.Printf(_("Not connected"));
632 }
633 else
634 {
635 wxIPV4address addr;
636
637 m_sock->GetPeer(addr);
638 s.Printf(_("%s : %d"), (addr.Hostname()).c_str(), addr.Service());
639 }
640
641 #if wxUSE_STATUSBAR
642 SetStatusText(s, 1);
643 #endif // wxUSE_STATUSBAR
644
645 m_menuSocket->Enable(CLIENT_OPEN, !m_sock->IsConnected() && !m_busy);
646 m_menuSocket->Enable(CLIENT_TEST1, m_sock->IsConnected() && !m_busy);
647 m_menuSocket->Enable(CLIENT_TEST2, m_sock->IsConnected() && !m_busy);
648 m_menuSocket->Enable(CLIENT_TEST3, m_sock->IsConnected() && !m_busy);
649 m_menuSocket->Enable(CLIENT_CLOSE, m_sock->IsConnected());
650 }