]> git.saurik.com Git - wxWidgets.git/blame - samples/sockets/client.cpp
set socket state to connected when it receives a connection notification, otherwise...
[wxWidgets.git] / samples / sockets / client.cpp
CommitLineData
f85d901f
GRG
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// --------------------------------------------------------------------------
e2a6f233 19
f85d901f 20// For compilers that support precompilation, includes "wx/wx.h".
f4ada568
GL
21#include "wx/wxprec.h"
22
23#ifdef __BORLANDC__
f85d901f 24# pragma hdrstop
f4ada568
GL
25#endif
26
925e9792 27// for all others, include the necessary headers
f4ada568 28#ifndef WX_PRECOMP
f85d901f 29# include "wx/wx.h"
09fb22cf
JS
30#endif
31
6097c3a2
GRG
32#include "wx/socket.h"
33#include "wx/url.h"
1e4080f0 34#include "wx/sstream.h"
1e4080f0 35#include <memory>
e2a6f233 36
f85d901f
GRG
37// --------------------------------------------------------------------------
38// resources
39// --------------------------------------------------------------------------
f4ada568 40
f85d901f 41// the application icon
2804f77d 42#include "mondrian.xpm"
e2a6f233 43
f85d901f
GRG
44// --------------------------------------------------------------------------
45// classes
46// --------------------------------------------------------------------------
f4ada568 47
f85d901f
GRG
48// Define a new application type
49class MyApp : public wxApp
50{
f4ada568 51public:
f85d901f 52 virtual bool OnInit();
f4ada568
GL
53};
54
f85d901f
GRG
55// Define a new frame type: this is going to be our main frame
56class MyFrame : public wxFrame
f4ada568
GL
57{
58public:
f85d901f
GRG
59 MyFrame();
60 ~MyFrame();
61
25ba2b89 62 // event handlers for File menu
f85d901f
GRG
63 void OnQuit(wxCommandEvent& event);
64 void OnAbout(wxCommandEvent& event);
25ba2b89
GRG
65
66 // event handlers for Socket menu
f85d901f
GRG
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);
25ba2b89 72
16cafacf 73#if wxUSE_URL
25ba2b89
GRG
74 // event handlers for Protocols menu
75 void OnTestURL(wxCommandEvent& event);
16cafacf 76#endif
8575ff50
VZ
77#if wxUSE_IPV6
78 void OnOpenConnectionIPv6(wxCommandEvent& event);
79#endif
80
778f682e 81 void OpenConnection(wxSockAddress::Family family);
25ba2b89 82
e51b0130 83 // event handlers for DatagramSocket menu (stub)
6097c3a2 84 void OnDatagram(wxCommandEvent& event);
f85d901f 85
25ba2b89
GRG
86 // socket event handler
87 void OnSocketEvent(wxSocketEvent& event);
88
f85d901f
GRG
89 // convenience functions
90 void UpdateStatusBar();
91
92private:
93 wxSocketClient *m_sock;
f85d901f
GRG
94 wxTextCtrl *m_text;
95 wxMenu *m_menuFile;
96 wxMenu *m_menuSocket;
6097c3a2 97 wxMenu *m_menuDatagramSocket;
25ba2b89 98 wxMenu *m_menuProtocols;
f85d901f
GRG
99 wxMenuBar *m_menuBar;
100 bool m_busy;
101
be5a51fb 102 // any class wishing to process wxWidgets events must use this macro
f85d901f 103 DECLARE_EVENT_TABLE()
f4ada568
GL
104};
105
f98f168e
VZ
106// simple helper class to log start and end of each test
107class TestLogger
108{
109public:
110 TestLogger(const wxString& name) : m_name(name)
111 {
112 wxLogMessage("=== %s test begins ===", m_name);
113 }
114
115 ~TestLogger()
116 {
117 wxLogMessage("=== %s test ends ===", m_name);
118 }
119
120private:
121 const wxString m_name;
122};
123
f85d901f
GRG
124// --------------------------------------------------------------------------
125// constants
126// --------------------------------------------------------------------------
f4ada568 127
f85d901f
GRG
128// IDs for the controls and the menu commands
129enum
f4ada568 130{
f85d901f 131 // menu items
91b07357
JS
132 CLIENT_QUIT = wxID_EXIT,
133 CLIENT_ABOUT = wxID_ABOUT,
134 CLIENT_OPEN = 100,
8575ff50
VZ
135#if wxUSE_IPV6
136 CLIENT_OPENIPV6,
137#endif
f85d901f
GRG
138 CLIENT_TEST1,
139 CLIENT_TEST2,
140 CLIENT_TEST3,
141 CLIENT_CLOSE,
16cafacf 142#if wxUSE_URL
25ba2b89 143 CLIENT_TESTURL,
16cafacf 144#endif
6097c3a2 145 CLIENT_DGRAM,
f85d901f
GRG
146
147 // id for socket
148 SOCKET_ID
149};
f4ada568 150
f85d901f 151// --------------------------------------------------------------------------
be5a51fb 152// event tables and other macros for wxWidgets
f85d901f 153// --------------------------------------------------------------------------
f4ada568 154
f85d901f 155BEGIN_EVENT_TABLE(MyFrame, wxFrame)
25ba2b89
GRG
156 EVT_MENU(CLIENT_QUIT, MyFrame::OnQuit)
157 EVT_MENU(CLIENT_ABOUT, MyFrame::OnAbout)
158 EVT_MENU(CLIENT_OPEN, MyFrame::OnOpenConnection)
8575ff50
VZ
159#if wxUSE_IPV6
160 EVT_MENU(CLIENT_OPENIPV6, MyFrame::OnOpenConnectionIPv6)
161#endif
25ba2b89
GRG
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)
16cafacf 167#if wxUSE_URL
25ba2b89 168 EVT_MENU(CLIENT_TESTURL, MyFrame::OnTestURL)
16cafacf 169#endif
25ba2b89 170 EVT_SOCKET(SOCKET_ID, MyFrame::OnSocketEvent)
f85d901f 171END_EVENT_TABLE()
f4ada568 172
f85d901f 173IMPLEMENT_APP(MyApp)
f4ada568 174
f85d901f
GRG
175// ==========================================================================
176// implementation
177// ==========================================================================
f4ada568 178
f85d901f
GRG
179// --------------------------------------------------------------------------
180// the application class
181// --------------------------------------------------------------------------
f4ada568 182
f85d901f
GRG
183bool MyApp::OnInit()
184{
45e6e6f8
VZ
185 if ( !wxApp::OnInit() )
186 return false;
187
f85d901f
GRG
188 // Create the main application window
189 MyFrame *frame = new MyFrame();
f4ada568 190
f85d901f 191 // Show it and tell the application that it's our main window
b62ca03d 192 frame->Show(true);
f85d901f
GRG
193 SetTopWindow(frame);
194
195 // success
b62ca03d 196 return true;
f4ada568
GL
197}
198
f85d901f
GRG
199// --------------------------------------------------------------------------
200// main frame
201// --------------------------------------------------------------------------
202
203// frame constructor
b62ca03d 204MyFrame::MyFrame() : wxFrame((wxFrame *)NULL, wxID_ANY,
25ba2b89 205 _("wxSocket demo: Client"),
f85d901f 206 wxDefaultPosition, wxSize(300, 200))
f4ada568 207{
f85d901f
GRG
208 // Give the frame an icon
209 SetIcon(wxICON(mondrian));
210
211 // Make menus
212 m_menuFile = new wxMenu();
25ba2b89 213 m_menuFile->Append(CLIENT_ABOUT, _("&About...\tCtrl-A"), _("Show about dialog"));
f85d901f 214 m_menuFile->AppendSeparator();
25ba2b89 215 m_menuFile->Append(CLIENT_QUIT, _("E&xit\tAlt-X"), _("Quit client"));
f85d901f
GRG
216
217 m_menuSocket = new wxMenu();
9c22ef28 218 m_menuSocket->Append(CLIENT_OPEN, _("&Open session\tCtrl-O"), _("Connect to server"));
8575ff50 219#if wxUSE_IPV6
9c22ef28 220 m_menuSocket->Append(CLIENT_OPENIPV6, _("&Open session(IPv6)\tShift-Ctrl-O"), _("Connect to server(IPv6)"));
8575ff50 221#endif
f85d901f 222 m_menuSocket->AppendSeparator();
9c22ef28
VZ
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"));
f85d901f 226 m_menuSocket->AppendSeparator();
9c22ef28 227 m_menuSocket->Append(CLIENT_CLOSE, _("&Close session\tCtrl-Q"), _("Close connection"));
f85d901f 228
6097c3a2 229 m_menuDatagramSocket = new wxMenu();
46b11427 230 m_menuDatagramSocket->Append(CLIENT_DGRAM, _("&Datagram test\tCtrl-D"), _("Test UDP sockets"));
25ba2b89 231
16cafacf 232#if wxUSE_URL
25ba2b89 233 m_menuProtocols = new wxMenu();
1e4080f0
VZ
234 m_menuProtocols->Append(CLIENT_TESTURL, _("Test URL\tCtrl-U"),
235 _("Get data from the specified URL"));
16cafacf 236#endif
6097c3a2 237
f85d901f
GRG
238 // Append menus to the menubar
239 m_menuBar = new wxMenuBar();
25ba2b89 240 m_menuBar->Append(m_menuFile, _("&File"));
46b11427
VZ
241 m_menuBar->Append(m_menuSocket, _("&TCP"));
242 m_menuBar->Append(m_menuDatagramSocket, _("&UDP"));
16cafacf 243#if wxUSE_URL
25ba2b89 244 m_menuBar->Append(m_menuProtocols, _("&Protocols"));
16cafacf 245#endif
f85d901f
GRG
246 SetMenuBar(m_menuBar);
247
8520f137 248#if wxUSE_STATUSBAR
f85d901f 249 // Status bar
f4ada568 250 CreateStatusBar(2);
8520f137 251#endif // wxUSE_STATUSBAR
f85d901f 252
bd4d918f 253 // Make a textctrl for logging
b62ca03d 254 m_text = new wxTextCtrl(this, wxID_ANY,
4693b20c 255 _("Welcome to wxSocket demo: Client\nClient ready\n"),
bd4d918f 256 wxDefaultPosition, wxDefaultSize,
f85d901f 257 wxTE_MULTILINE | wxTE_READONLY);
1e4080f0 258 delete wxLog::SetActiveTarget(new wxLogTextCtrl(m_text));
f85d901f
GRG
259
260 // Create the socket
261 m_sock = new wxSocketClient();
bd4d918f
GRG
262
263 // Setup the event handler and subscribe to most events
f85d901f
GRG
264 m_sock->SetEventHandler(*this, SOCKET_ID);
265 m_sock->SetNotify(wxSOCKET_CONNECTION_FLAG |
266 wxSOCKET_INPUT_FLAG |
267 wxSOCKET_LOST_FLAG);
b62ca03d 268 m_sock->Notify(true);
f85d901f 269
b62ca03d 270 m_busy = false;
f85d901f 271 UpdateStatusBar();
f4ada568
GL
272}
273
274MyFrame::~MyFrame()
275{
bd4d918f 276 // No delayed deletion here, as the frame is dying anyway
f85d901f 277 delete m_sock;
f4ada568
GL
278}
279
f85d901f
GRG
280// event handlers
281
282void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
f4ada568 283{
b62ca03d
WS
284 // true is to force the frame to close
285 Close(true);
f4ada568
GL
286}
287
f85d901f
GRG
288void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
289{
4693b20c 290 wxMessageBox(_("wxSocket demo: Client\n(c) 1999 Guillermo Rodriguez Garcia\n"),
25ba2b89 291 _("About Client"),
f85d901f
GRG
292 wxOK | wxICON_INFORMATION, this);
293}
294
295void MyFrame::OnOpenConnection(wxCommandEvent& WXUNUSED(event))
f4ada568 296{
778f682e 297 OpenConnection(wxSockAddress::IPV4);
8575ff50
VZ
298}
299#if wxUSE_IPV6
300void MyFrame::OnOpenConnectionIPv6(wxCommandEvent& WXUNUSED(event))
301{
778f682e 302 OpenConnection(wxSockAddress::IPV6);
8575ff50
VZ
303}
304#endif // wxUSE_IPV6
305
778f682e 306void MyFrame::OpenConnection(wxSockAddress::Family family)
8575ff50 307{
778f682e
VZ
308 wxUnusedVar(family); // unused in !wxUSE_IPV6 case
309
8575ff50 310 wxIPaddress * addr;
25248cb6 311 wxIPV4address addr4;
8575ff50
VZ
312#if wxUSE_IPV6
313 wxIPV6address addr6;
778f682e 314 if ( family == wxSockAddress::IPV6 )
25248cb6
VZ
315 addr = &addr6;
316 else
8575ff50 317#endif
778f682e 318 addr = &addr4;
f4ada568 319
b62ca03d 320 m_menuSocket->Enable(CLIENT_OPEN, false);
8575ff50
VZ
321#if wxUSE_IPV6
322 m_menuSocket->Enable(CLIENT_OPENIPV6, false);
323#endif
b62ca03d 324 m_menuSocket->Enable(CLIENT_CLOSE, false);
f85d901f 325
25ba2b89 326 // Ask user for server address
f85d901f 327 wxString hostname = wxGetTextFromUser(
25ba2b89
GRG
328 _("Enter the address of the wxSocket demo server:"),
329 _("Connect ..."),
330 _("localhost"));
46b11427
VZ
331 if ( hostname.empty() )
332 return;
f85d901f 333
8575ff50
VZ
334 addr->Hostname(hostname);
335 addr->Service(3000);
f4ada568 336
25ba2b89
GRG
337 // Mini-tutorial for Connect() :-)
338 // ---------------------------
339 //
340 // There are two ways to use Connect(): blocking and non-blocking,
341 // depending on the value passed as the 'wait' (2nd) parameter.
342 //
b62ca03d
WS
343 // Connect(addr, true) will wait until the connection completes,
344 // returning true on success and false on failure. This call blocks
25ba2b89
GRG
345 // the GUI (this might be changed in future releases to honour the
346 // wxSOCKET_BLOCK flag).
347 //
b62ca03d
WS
348 // Connect(addr, false) will issue a nonblocking connection request
349 // and return immediately. If the return value is true, then the
3103e8a9 350 // connection has been already successfully established. If it is
b62ca03d 351 // false, you must wait for the request to complete, either with
25ba2b89
GRG
352 // WaitOnConnect() or by watching wxSOCKET_CONNECTION / LOST
353 // events (please read the documentation).
354 //
355 // WaitOnConnect() itself never blocks the GUI (this might change
356 // in the future to honour the wxSOCKET_BLOCK flag). This call will
b62ca03d 357 // return false on timeout, or true if the connection request
bd4d918f
GRG
358 // completes, which in turn might mean:
359 //
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.
363 //
25ba2b89
GRG
364 // Use IsConnected() to distinguish between these two.
365 //
366 // So, in a brief, you should do one of the following things:
367 //
368 // For blocking Connect:
369 //
b62ca03d 370 // bool success = client->Connect(addr, true);
25ba2b89
GRG
371 //
372 // For nonblocking Connect:
373 //
b62ca03d 374 // client->Connect(addr, false);
bd4d918f 375 //
b62ca03d 376 // bool waitmore = true;
a85139a1 377 // while (! client->WaitOnConnect(seconds, millis) && waitmore )
bd4d918f
GRG
378 // {
379 // // possibly give some feedback to the user,
380 // // update waitmore if needed.
381 // }
a85139a1 382 // bool success = client->IsConnected();
925e9792 383 //
25ba2b89 384 // And that's all :-)
e51b0130 385
25ba2b89 386 m_text->AppendText(_("\nTrying to connect (timeout = 10 sec) ...\n"));
8575ff50 387 m_sock->Connect(*addr, false);
25ba2b89 388 m_sock->WaitOnConnect(10);
f85d901f
GRG
389
390 if (m_sock->IsConnected())
25ba2b89 391 m_text->AppendText(_("Succeeded ! Connection established\n"));
f85d901f
GRG
392 else
393 {
394 m_sock->Close();
25ba2b89
GRG
395 m_text->AppendText(_("Failed ! Unable to connect\n"));
396 wxMessageBox(_("Can't connect to the specified host"), _("Alert !"));
f85d901f 397 }
925e9792 398
f85d901f 399 UpdateStatusBar();
f4ada568
GL
400}
401
f85d901f 402void MyFrame::OnTest1(wxCommandEvent& WXUNUSED(event))
f4ada568 403{
f85d901f 404 // Disable socket menu entries (exception: Close Session)
b62ca03d 405 m_busy = true;
f85d901f
GRG
406 UpdateStatusBar();
407
25ba2b89 408 m_text->AppendText(_("\n=== Test 1 begins ===\n"));
f85d901f
GRG
409
410 // Tell the server which test we are running
f4d5e009 411 unsigned char c = 0xBE;
f85d901f
GRG
412 m_sock->Write(&c, 1);
413
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
6097c3a2
GRG
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.
f85d901f
GRG
419 //
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
6097c3a2 422 // value larger than a byte "as is" across the network, or
f85d901f
GRG
423 // you might be in trouble! Ever heard about big and little
424 // endian computers?)
e51b0130 425
f85d901f
GRG
426 m_sock->SetFlags(wxSOCKET_WAITALL);
427
9c22ef28
VZ
428 const char *buf1 = "Test string (less than 256 chars!)";
429 unsigned char len = (unsigned char)(wxStrlen(buf1) + 1);
430 wxCharBuffer buf2(wxStrlen(buf1));
f85d901f 431
25ba2b89 432 m_text->AppendText(_("Sending a test buffer to the server ..."));
f187448d 433 m_sock->Write(&len, 1);
f85d901f 434 m_sock->Write(buf1, len);
25ba2b89 435 m_text->AppendText(m_sock->Error() ? _("failed !\n") : _("done\n"));
f85d901f 436
25ba2b89 437 m_text->AppendText(_("Receiving the buffer back from server ..."));
9c22ef28 438 m_sock->Read(buf2.data(), len);
25ba2b89 439 m_text->AppendText(m_sock->Error() ? _("failed !\n") : _("done\n"));
f85d901f 440
25ba2b89 441 m_text->AppendText(_("Comparing the two buffers ..."));
f85d901f
GRG
442 if (memcmp(buf1, buf2, len) != 0)
443 {
25ba2b89
GRG
444 m_text->AppendText(_("failed!\n"));
445 m_text->AppendText(_("Test 1 failed !\n"));
f85d901f
GRG
446 }
447 else
448 {
25ba2b89
GRG
449 m_text->AppendText(_("done\n"));
450 m_text->AppendText(_("Test 1 passed !\n"));
f85d901f 451 }
25ba2b89 452 m_text->AppendText(_("=== Test 1 ends ===\n"));
f4ada568 453
b62ca03d 454 m_busy = false;
f85d901f
GRG
455 UpdateStatusBar();
456}
f4ada568 457
f85d901f
GRG
458void MyFrame::OnTest2(wxCommandEvent& WXUNUSED(event))
459{
f85d901f 460 // Disable socket menu entries (exception: Close Session)
b62ca03d 461 m_busy = true;
f85d901f
GRG
462 UpdateStatusBar();
463
25ba2b89 464 m_text->AppendText(_("\n=== Test 2 begins ===\n"));
f85d901f
GRG
465
466 // Tell the server which test we are running
f4d5e009 467 unsigned char c = 0xCE;
f85d901f
GRG
468 m_sock->Write(&c, 1);
469
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.
473 //
474 // We need to set no flags here (ReadMsg and WriteMsg are
475 // not affected by flags)
e51b0130 476
f85d901f
GRG
477 m_sock->SetFlags(wxSOCKET_WAITALL);
478
479 wxString s = wxGetTextFromUser(
25ba2b89
GRG
480 _("Enter an arbitrary string to send to the server:"),
481 _("Test 2 ..."),
be5a51fb 482 _("Yes I like wxWidgets!"));
f85d901f 483
197380a0 484 const wxScopedCharBuffer msg1(s.utf8_str());
9c22ef28
VZ
485 size_t len = wxStrlen(msg1) + 1;
486 wxCharBuffer msg2(wxStrlen(msg1));
f85d901f 487
25ba2b89 488 m_text->AppendText(_("Sending the string with WriteMsg ..."));
f85d901f 489 m_sock->WriteMsg(msg1, len);
25ba2b89
GRG
490 m_text->AppendText(m_sock->Error() ? _("failed !\n") : _("done\n"));
491 m_text->AppendText(_("Waiting for an event (timeout = 2 sec)\n"));
f85d901f
GRG
492
493 // Wait until data available (will also return if the connection is lost)
494 m_sock->WaitForRead(2);
495
496 if (m_sock->IsData())
497 {
25ba2b89 498 m_text->AppendText(_("Reading the string back with ReadMsg ..."));
9c22ef28 499 m_sock->ReadMsg(msg2.data(), len);
25ba2b89
GRG
500 m_text->AppendText(m_sock->Error() ? _("failed !\n") : _("done\n"));
501 m_text->AppendText(_("Comparing the two buffers ..."));
f85d901f
GRG
502 if (memcmp(msg1, msg2, len) != 0)
503 {
925e9792 504 m_text->AppendText(_("failed!\n"));
25ba2b89 505 m_text->AppendText(_("Test 2 failed !\n"));
f85d901f
GRG
506 }
507 else
508 {
25ba2b89
GRG
509 m_text->AppendText(_("done\n"));
510 m_text->AppendText(_("Test 2 passed !\n"));
f85d901f 511 }
765e386b 512 }
f85d901f 513 else
25ba2b89 514 m_text->AppendText(_("Timeout ! Test 2 failed.\n"));
765e386b 515
25ba2b89 516 m_text->AppendText(_("=== Test 2 ends ===\n"));
765e386b 517
b62ca03d 518 m_busy = false;
f85d901f 519 UpdateStatusBar();
765e386b
GL
520}
521
f85d901f 522void MyFrame::OnTest3(wxCommandEvent& WXUNUSED(event))
f4ada568 523{
6097c3a2 524 // Disable socket menu entries (exception: Close Session)
b62ca03d 525 m_busy = true;
6097c3a2
GRG
526 UpdateStatusBar();
527
25ba2b89 528 m_text->AppendText(_("\n=== Test 3 begins ===\n"));
6097c3a2
GRG
529
530 // Tell the server which test we are running
f4d5e009 531 unsigned char c = 0xDE;
6097c3a2
GRG
532 m_sock->Write(&c, 1);
533
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
537 // returning.
e51b0130 538
6097c3a2
GRG
539 m_sock->SetFlags(wxSOCKET_WAITALL);
540
541 // Note that len is in kbytes here!
9c22ef28
VZ
542 const unsigned char len = 32;
543 wxCharBuffer buf1(len * 1024),
544 buf2(len * 1024);
6097c3a2 545
9c22ef28
VZ
546 for (size_t i = 0; i < len * 1024; i ++)
547 buf1.data()[i] = (char)(i % 256);
6097c3a2 548
25ba2b89 549 m_text->AppendText(_("Sending a large buffer (32K) to the server ..."));
f187448d 550 m_sock->Write(&len, 1);
6097c3a2 551 m_sock->Write(buf1, len * 1024);
25ba2b89 552 m_text->AppendText(m_sock->Error() ? _("failed !\n") : _("done\n"));
6097c3a2 553
25ba2b89 554 m_text->AppendText(_("Receiving the buffer back from server ..."));
9c22ef28 555 m_sock->Read(buf2.data(), len * 1024);
25ba2b89 556 m_text->AppendText(m_sock->Error() ? _("failed !\n") : _("done\n"));
6097c3a2 557
25ba2b89 558 m_text->AppendText(_("Comparing the two buffers ..."));
6097c3a2
GRG
559 if (memcmp(buf1, buf2, len) != 0)
560 {
25ba2b89
GRG
561 m_text->AppendText(_("failed!\n"));
562 m_text->AppendText(_("Test 3 failed !\n"));
6097c3a2
GRG
563 }
564 else
565 {
25ba2b89
GRG
566 m_text->AppendText(_("done\n"));
567 m_text->AppendText(_("Test 3 passed !\n"));
6097c3a2 568 }
25ba2b89 569 m_text->AppendText(_("=== Test 3 ends ===\n"));
6097c3a2 570
b62ca03d 571 m_busy = false;
6097c3a2 572 UpdateStatusBar();
f4ada568
GL
573}
574
f85d901f 575void MyFrame::OnCloseConnection(wxCommandEvent& WXUNUSED(event))
f4ada568 576{
f85d901f
GRG
577 m_sock->Close();
578 UpdateStatusBar();
f4ada568
GL
579}
580
6097c3a2
GRG
581void MyFrame::OnDatagram(wxCommandEvent& WXUNUSED(event))
582{
46b11427
VZ
583 wxString hostname = wxGetTextFromUser
584 (
585 "Enter the address of the wxSocket demo server:",
586 "UDP peer",
587 "localhost"
588 );
589 if ( hostname.empty() )
590 return;
591
592 TestLogger logtest("UDP");
593
594 wxIPV4address addrLocal;
595 addrLocal.Hostname();
596 wxDatagramSocket sock(addrLocal);
597 if ( !sock.IsOk() )
598 {
599 wxLogMessage("ERROR: failed to create UDP socket");
600 return;
601 }
602
603 wxLogMessage("Created UDP socket at %s:%u",
604 addrLocal.IPAddress(), addrLocal.Service());
605
606 wxIPV4address addrPeer;
607 addrPeer.Hostname(hostname);
608 addrPeer.Service(3000);
609
610 wxLogMessage("Testing UDP with peer at %s:%u",
611 addrPeer.IPAddress(), addrPeer.Service());
612
613 char buf[] = "Uryyb sebz pyvrag!";
614 if ( sock.SendTo(addrPeer, buf, sizeof(buf)).LastCount() != sizeof(buf) )
615 {
616 wxLogMessage("ERROR: failed to send data");
617 return;
618 }
619
620 if ( sock.RecvFrom(addrPeer, buf, sizeof(buf)).LastCount() != sizeof(buf) )
621 {
622 wxLogMessage("ERROR: failed to receive data");
623 return;
624 }
625
626 wxLogMessage("Received \"%s\" from %s:%u.",
627 wxString::From8BitData(buf, sock.LastCount()),
628 addrPeer.IPAddress(), addrPeer.Service());
6097c3a2
GRG
629}
630
16cafacf
RN
631#if wxUSE_URL
632
25ba2b89
GRG
633void MyFrame::OnTestURL(wxCommandEvent& WXUNUSED(event))
634{
1e4080f0
VZ
635 // Ask for the URL
636 static wxString s_urlname("http://www.google.com/");
637 wxString urlname = wxGetTextFromUser
638 (
639 _("Enter an URL to get"),
640 _("URL:"),
641 s_urlname
642 );
643 if ( urlname.empty() )
644 return; // cancelled by user
645
646 s_urlname = urlname;
647
648
f98f168e 649 TestLogger logtest("URL");
1e4080f0
VZ
650
651 // Parse the URL
652 wxURL url(urlname);
653 if ( url.GetError() != wxURL_NOERR )
654 {
655 wxLogError("Failed to parse URL \"%s\"", urlname);
656 return;
657 }
25ba2b89 658
1e4080f0
VZ
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());
662 if ( !data.get() )
663 {
664 wxLogError("Failed to retrieve URL \"%s\"", urlname);
665 return;
666 }
25ba2b89 667
1e4080f0
VZ
668 // Print the contents type and file size
669 wxLogMessage("Contents type: %s\nFile size: %i\nStarting to download...",
670 url.GetProtocol().GetContentType(),
671 data->GetSize());
6f505cae 672
1e4080f0
VZ
673 // Get the data
674 wxStringOutputStream sout;
675 if ( data->Read(sout).GetLastError() != wxSTREAM_EOF )
676 wxLogError("Error reading the input stream.");
25ba2b89 677
1e4080f0
VZ
678 wxLogMessage("Text retrieved from URL \"%s\" follows:\n%s",
679 urlname, sout.GetString());
25ba2b89
GRG
680}
681
1e4080f0 682#endif // wxUSE_URL
16cafacf 683
f85d901f 684void MyFrame::OnSocketEvent(wxSocketEvent& event)
f4ada568 685{
25ba2b89 686 wxString s = _("OnSocketEvent: ");
f85d901f 687
bc7e88ae 688 switch(event.GetSocketEvent())
f85d901f 689 {
25ba2b89
GRG
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;
f85d901f 694 }
f4ada568 695
f85d901f
GRG
696 m_text->AppendText(s);
697 UpdateStatusBar();
f4ada568
GL
698}
699
f85d901f 700// convenience functions
a324a7bc 701
f85d901f 702void MyFrame::UpdateStatusBar()
a324a7bc 703{
f85d901f 704 wxString s;
a324a7bc 705
f85d901f
GRG
706 if (!m_sock->IsConnected())
707 {
25ba2b89 708 s.Printf(_("Not connected"));
a324a7bc 709 }
f85d901f
GRG
710 else
711 {
8575ff50
VZ
712#if wxUSE_IPV6
713 wxIPV6address addr;
714#else
f85d901f 715 wxIPV4address addr;
8575ff50 716#endif
a324a7bc 717
f85d901f 718 m_sock->GetPeer(addr);
25ba2b89 719 s.Printf(_("%s : %d"), (addr.Hostname()).c_str(), addr.Service());
f85d901f 720 }
f4ada568 721
8520f137 722#if wxUSE_STATUSBAR
f85d901f 723 SetStatusText(s, 1);
8520f137 724#endif // wxUSE_STATUSBAR
a737331d 725
f85d901f 726 m_menuSocket->Enable(CLIENT_OPEN, !m_sock->IsConnected() && !m_busy);
8575ff50
VZ
727#if wxUSE_IPV6
728 m_menuSocket->Enable(CLIENT_OPENIPV6, !m_sock->IsConnected() && !m_busy);
729#endif
f85d901f
GRG
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());
f4ada568 734}