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