]>
git.saurik.com Git - wxWidgets.git/blob - samples/sockets/client.cpp
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/wfstream.h"
36 // --------------------------------------------------------------------------
38 // --------------------------------------------------------------------------
40 // the application icon
41 #if defined(__WXGTK__) || defined(__WXX11__) || defined(__WXMOTIF__) || defined(__WXMAC__)
42 # include "mondrian.xpm"
45 // --------------------------------------------------------------------------
47 // --------------------------------------------------------------------------
49 // Define a new application type
50 class MyApp
: public wxApp
53 virtual bool OnInit();
56 // Define a new frame type: this is going to be our main frame
57 class MyFrame
: public wxFrame
63 // event handlers for File menu
64 void OnQuit(wxCommandEvent
& event
);
65 void OnAbout(wxCommandEvent
& event
);
67 // event handlers for Socket menu
68 void OnOpenConnection(wxCommandEvent
& event
);
69 void OnTest1(wxCommandEvent
& event
);
70 void OnTest2(wxCommandEvent
& event
);
71 void OnTest3(wxCommandEvent
& event
);
72 void OnCloseConnection(wxCommandEvent
& event
);
75 // event handlers for Protocols menu
76 void OnTestURL(wxCommandEvent
& event
);
79 void OnOpenConnectionIPv6(wxCommandEvent
& event
);
82 void OpenConnection(int family
= AF_INET
);
84 // event handlers for DatagramSocket menu (stub)
85 void OnDatagram(wxCommandEvent
& event
);
87 // socket event handler
88 void OnSocketEvent(wxSocketEvent
& event
);
90 // convenience functions
91 void UpdateStatusBar();
94 wxSocketClient
*m_sock
;
98 wxMenu
*m_menuDatagramSocket
;
99 wxMenu
*m_menuProtocols
;
100 wxMenuBar
*m_menuBar
;
103 // any class wishing to process wxWidgets events must use this macro
104 DECLARE_EVENT_TABLE()
107 // --------------------------------------------------------------------------
109 // --------------------------------------------------------------------------
111 // IDs for the controls and the menu commands
115 CLIENT_QUIT
= wxID_EXIT
,
116 CLIENT_ABOUT
= wxID_ABOUT
,
134 // --------------------------------------------------------------------------
135 // event tables and other macros for wxWidgets
136 // --------------------------------------------------------------------------
138 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
139 EVT_MENU(CLIENT_QUIT
, MyFrame::OnQuit
)
140 EVT_MENU(CLIENT_ABOUT
, MyFrame::OnAbout
)
141 EVT_MENU(CLIENT_OPEN
, MyFrame::OnOpenConnection
)
143 EVT_MENU(CLIENT_OPENIPV6
, MyFrame::OnOpenConnectionIPv6
)
145 EVT_MENU(CLIENT_TEST1
, MyFrame::OnTest1
)
146 EVT_MENU(CLIENT_TEST2
, MyFrame::OnTest2
)
147 EVT_MENU(CLIENT_TEST3
, MyFrame::OnTest3
)
148 EVT_MENU(CLIENT_CLOSE
, MyFrame::OnCloseConnection
)
149 EVT_MENU(CLIENT_DGRAM
, MyFrame::OnDatagram
)
151 EVT_MENU(CLIENT_TESTURL
, MyFrame::OnTestURL
)
153 EVT_SOCKET(SOCKET_ID
, MyFrame::OnSocketEvent
)
158 // ==========================================================================
160 // ==========================================================================
162 // --------------------------------------------------------------------------
163 // the application class
164 // --------------------------------------------------------------------------
168 if ( !wxApp::OnInit() )
171 // Create the main application window
172 MyFrame
*frame
= new MyFrame();
174 // Show it and tell the application that it's our main window
182 // --------------------------------------------------------------------------
184 // --------------------------------------------------------------------------
187 MyFrame::MyFrame() : wxFrame((wxFrame
*)NULL
, wxID_ANY
,
188 _("wxSocket demo: Client"),
189 wxDefaultPosition
, wxSize(300, 200))
191 // Give the frame an icon
192 SetIcon(wxICON(mondrian
));
195 m_menuFile
= new wxMenu();
196 m_menuFile
->Append(CLIENT_ABOUT
, _("&About...\tCtrl-A"), _("Show about dialog"));
197 m_menuFile
->AppendSeparator();
198 m_menuFile
->Append(CLIENT_QUIT
, _("E&xit\tAlt-X"), _("Quit client"));
200 m_menuSocket
= new wxMenu();
201 m_menuSocket
->Append(CLIENT_OPEN
, _("&Open session"), _("Connect to server"));
203 m_menuSocket
->Append(CLIENT_OPENIPV6
, _("&Open session(IPv6)"), _("Connect to server(IPv6)"));
205 m_menuSocket
->AppendSeparator();
206 m_menuSocket
->Append(CLIENT_TEST1
, _("Test &1"), _("Test basic functionality"));
207 m_menuSocket
->Append(CLIENT_TEST2
, _("Test &2"), _("Test ReadMsg and WriteMsg"));
208 m_menuSocket
->Append(CLIENT_TEST3
, _("Test &3"), _("Test large data transfer"));
209 m_menuSocket
->AppendSeparator();
210 m_menuSocket
->Append(CLIENT_CLOSE
, _("&Close session"), _("Close connection"));
212 m_menuDatagramSocket
= new wxMenu();
213 m_menuDatagramSocket
->Append(CLIENT_DGRAM
, _("Send Datagram"), _("Test UDP sockets"));
216 m_menuProtocols
= new wxMenu();
217 m_menuProtocols
->Append(CLIENT_TESTURL
, _("Test URL"), _("Get data from the specified URL"));
220 // Append menus to the menubar
221 m_menuBar
= new wxMenuBar();
222 m_menuBar
->Append(m_menuFile
, _("&File"));
223 m_menuBar
->Append(m_menuSocket
, _("&SocketClient"));
224 m_menuBar
->Append(m_menuDatagramSocket
, _("&DatagramSocket"));
226 m_menuBar
->Append(m_menuProtocols
, _("&Protocols"));
228 SetMenuBar(m_menuBar
);
233 #endif // wxUSE_STATUSBAR
235 // Make a textctrl for logging
236 m_text
= new wxTextCtrl(this, wxID_ANY
,
237 _("Welcome to wxSocket demo: Client\nClient ready\n"),
238 wxDefaultPosition
, wxDefaultSize
,
239 wxTE_MULTILINE
| wxTE_READONLY
);
242 m_sock
= new wxSocketClient();
244 // Setup the event handler and subscribe to most events
245 m_sock
->SetEventHandler(*this, SOCKET_ID
);
246 m_sock
->SetNotify(wxSOCKET_CONNECTION_FLAG
|
247 wxSOCKET_INPUT_FLAG
|
249 m_sock
->Notify(true);
257 // No delayed deletion here, as the frame is dying anyway
263 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
265 // true is to force the frame to close
269 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
271 wxMessageBox(_("wxSocket demo: Client\n(c) 1999 Guillermo Rodriguez Garcia\n"),
273 wxOK
| wxICON_INFORMATION
, this);
276 void MyFrame::OnOpenConnection(wxCommandEvent
& WXUNUSED(event
))
278 OpenConnection(AF_INET
);
281 void MyFrame::OnOpenConnectionIPv6(wxCommandEvent
& WXUNUSED(event
))
283 OpenConnection(AF_INET6
);
287 void MyFrame::OpenConnection(int family
)
293 if ( family
==AF_INET6
)
302 m_menuSocket
->Enable(CLIENT_OPEN
, false);
304 m_menuSocket
->Enable(CLIENT_OPENIPV6
, false);
306 m_menuSocket
->Enable(CLIENT_CLOSE
, false);
308 // Ask user for server address
309 wxString hostname
= wxGetTextFromUser(
310 _("Enter the address of the wxSocket demo server:"),
314 addr
->Hostname(hostname
);
317 // Mini-tutorial for Connect() :-)
318 // ---------------------------
320 // There are two ways to use Connect(): blocking and non-blocking,
321 // depending on the value passed as the 'wait' (2nd) parameter.
323 // Connect(addr, true) will wait until the connection completes,
324 // returning true on success and false on failure. This call blocks
325 // the GUI (this might be changed in future releases to honour the
326 // wxSOCKET_BLOCK flag).
328 // Connect(addr, false) will issue a nonblocking connection request
329 // and return immediately. If the return value is true, then the
330 // connection has been already successfully established. If it is
331 // false, you must wait for the request to complete, either with
332 // WaitOnConnect() or by watching wxSOCKET_CONNECTION / LOST
333 // events (please read the documentation).
335 // WaitOnConnect() itself never blocks the GUI (this might change
336 // in the future to honour the wxSOCKET_BLOCK flag). This call will
337 // return false on timeout, or true if the connection request
338 // completes, which in turn might mean:
340 // a) That the connection was successfully established
341 // b) That the connection request failed (for example, because
342 // it was refused by the peer.
344 // Use IsConnected() to distinguish between these two.
346 // So, in a brief, you should do one of the following things:
348 // For blocking Connect:
350 // bool success = client->Connect(addr, true);
352 // For nonblocking Connect:
354 // client->Connect(addr, false);
356 // bool waitmore = true;
357 // while (! client->WaitOnConnect(seconds, millis) && waitmore )
359 // // possibly give some feedback to the user,
360 // // update waitmore if needed.
362 // bool success = client->IsConnected();
364 // And that's all :-)
366 m_text
->AppendText(_("\nTrying to connect (timeout = 10 sec) ...\n"));
367 m_sock
->Connect(*addr
, false);
368 m_sock
->WaitOnConnect(10);
370 if (m_sock
->IsConnected())
371 m_text
->AppendText(_("Succeeded ! Connection established\n"));
375 m_text
->AppendText(_("Failed ! Unable to connect\n"));
376 wxMessageBox(_("Can't connect to the specified host"), _("Alert !"));
382 void MyFrame::OnTest1(wxCommandEvent
& WXUNUSED(event
))
384 // Disable socket menu entries (exception: Close Session)
388 m_text
->AppendText(_("\n=== Test 1 begins ===\n"));
390 // Tell the server which test we are running
391 unsigned char c
= 0xBE;
392 m_sock
->Write(&c
, 1);
394 // Send some data and read it back. We know the size of the
395 // buffer, so we can specify the exact number of bytes to be
396 // sent or received and use the wxSOCKET_WAITALL flag. Also,
397 // we have disabled menu entries which could interfere with
398 // the test, so we can safely avoid the wxSOCKET_BLOCK flag.
400 // First we send a byte with the length of the string, then
401 // we send the string itself (do NOT try to send any integral
402 // value larger than a byte "as is" across the network, or
403 // you might be in trouble! Ever heard about big and little
404 // endian computers?)
406 m_sock
->SetFlags(wxSOCKET_WAITALL
);
408 const wxChar
*buf1
= _T("Test string (less than 256 chars!)");
409 unsigned char len
= (unsigned char)((wxStrlen(buf1
) + 1)*sizeof(wxChar
));
410 wxChar
*buf2
= new wxChar
[wxStrlen(buf1
) + 1];
412 m_text
->AppendText(_("Sending a test buffer to the server ..."));
413 m_sock
->Write(&len
, 1);
414 m_sock
->Write(buf1
, len
);
415 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
417 m_text
->AppendText(_("Receiving the buffer back from server ..."));
418 m_sock
->Read(buf2
, len
);
419 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
421 m_text
->AppendText(_("Comparing the two buffers ..."));
422 if (memcmp(buf1
, buf2
, len
) != 0)
424 m_text
->AppendText(_("failed!\n"));
425 m_text
->AppendText(_("Test 1 failed !\n"));
429 m_text
->AppendText(_("done\n"));
430 m_text
->AppendText(_("Test 1 passed !\n"));
432 m_text
->AppendText(_("=== Test 1 ends ===\n"));
439 void MyFrame::OnTest2(wxCommandEvent
& WXUNUSED(event
))
445 // Disable socket menu entries (exception: Close Session)
449 m_text
->AppendText(_("\n=== Test 2 begins ===\n"));
451 // Tell the server which test we are running
452 unsigned char c
= 0xCE;
453 m_sock
->Write(&c
, 1);
455 // Here we use ReadMsg and WriteMsg to send messages with
456 // a header with size information. Also, the reception is
457 // event triggered, so we test input events as well.
459 // We need to set no flags here (ReadMsg and WriteMsg are
460 // not affected by flags)
462 m_sock
->SetFlags(wxSOCKET_WAITALL
);
464 wxString s
= wxGetTextFromUser(
465 _("Enter an arbitrary string to send to the server:"),
467 _("Yes I like wxWidgets!"));
470 len
= (wxStrlen(msg1
) + 1) * sizeof(wxChar
);
471 msg2
= new wxChar
[wxStrlen(msg1
) + 1];
473 m_text
->AppendText(_("Sending the string with WriteMsg ..."));
474 m_sock
->WriteMsg(msg1
, len
);
475 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
476 m_text
->AppendText(_("Waiting for an event (timeout = 2 sec)\n"));
478 // Wait until data available (will also return if the connection is lost)
479 m_sock
->WaitForRead(2);
481 if (m_sock
->IsData())
483 m_text
->AppendText(_("Reading the string back with ReadMsg ..."));
484 m_sock
->ReadMsg(msg2
, len
);
485 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
486 m_text
->AppendText(_("Comparing the two buffers ..."));
487 if (memcmp(msg1
, msg2
, len
) != 0)
489 m_text
->AppendText(_("failed!\n"));
490 m_text
->AppendText(_("Test 2 failed !\n"));
494 m_text
->AppendText(_("done\n"));
495 m_text
->AppendText(_("Test 2 passed !\n"));
499 m_text
->AppendText(_("Timeout ! Test 2 failed.\n"));
501 m_text
->AppendText(_("=== Test 2 ends ===\n"));
508 void MyFrame::OnTest3(wxCommandEvent
& WXUNUSED(event
))
514 // Disable socket menu entries (exception: Close Session)
518 m_text
->AppendText(_("\n=== Test 3 begins ===\n"));
520 // Tell the server which test we are running
521 unsigned char c
= 0xDE;
522 m_sock
->Write(&c
, 1);
524 // This test also is similar to the first one but it sends a
525 // large buffer so that wxSocket is actually forced to split
526 // it into pieces and take care of sending everything before
529 m_sock
->SetFlags(wxSOCKET_WAITALL
);
531 // Note that len is in kbytes here!
533 buf1
= new char[len
* 1024];
534 buf2
= new char[len
* 1024];
536 for (int i
= 0; i
< len
* 1024; i
++)
537 buf1
[i
] = (char)(i
% 256);
539 m_text
->AppendText(_("Sending a large buffer (32K) to the server ..."));
540 m_sock
->Write(&len
, 1);
541 m_sock
->Write(buf1
, len
* 1024);
542 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
544 m_text
->AppendText(_("Receiving the buffer back from server ..."));
545 m_sock
->Read(buf2
, len
* 1024);
546 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
548 m_text
->AppendText(_("Comparing the two buffers ..."));
549 if (memcmp(buf1
, buf2
, len
) != 0)
551 m_text
->AppendText(_("failed!\n"));
552 m_text
->AppendText(_("Test 3 failed !\n"));
556 m_text
->AppendText(_("done\n"));
557 m_text
->AppendText(_("Test 3 passed !\n"));
559 m_text
->AppendText(_("=== Test 3 ends ===\n"));
566 void MyFrame::OnCloseConnection(wxCommandEvent
& WXUNUSED(event
))
572 void MyFrame::OnDatagram(wxCommandEvent
& WXUNUSED(event
))
574 m_text
->AppendText(_("\n=== Datagram test begins ===\n"));
575 m_text
->AppendText(_("Sorry, not implemented\n"));
576 m_text
->AppendText(_("=== Datagram test ends ===\n"));
581 void MyFrame::OnTestURL(wxCommandEvent
& WXUNUSED(event
))
583 // Note that we are creating a new socket here, so this
584 // won't mess with the client/server demo.
587 m_text
->AppendText(_("\n=== URL test begins ===\n"));
588 wxString urlname
= wxGetTextFromUser(_("Enter an URL to get"),
590 _T("http://localhost"));
594 if (url
.GetError() != wxURL_NOERR
)
596 m_text
->AppendText(_("Error: couldn't parse URL\n"));
597 m_text
->AppendText(_("=== URL test ends ===\n"));
601 // Try to get the input stream (connects to the given URL)
602 m_text
->AppendText(_("Trying to establish connection...\n"));
604 wxInputStream
*data
= url
.GetInputStream();
607 m_text
->AppendText(_("Error: couldn't read from URL\n"));
608 m_text
->AppendText(_("=== URL test ends ===\n"));
612 // Print the contents type and file size
614 s
.Printf(_("Contents type: %s\nFile size: %i\nStarting to download...\n"),
615 url
.GetProtocol().GetContentType().c_str(),
617 m_text
->AppendText(s
);
621 wxFile
fileTest(wxT("test.url"), wxFile::write
);
622 wxFileOutputStream
sout(fileTest
);
625 m_text
->AppendText(_("Error: couldn't open file for output\n"));
626 m_text
->AppendText(_("=== URL test ends ===\n"));
631 m_text
->AppendText(_("Results written to file: test.url\n"));
632 m_text
->AppendText(_("Done.\n"));
633 m_text
->AppendText(_("=== URL test ends ===\n"));
640 void MyFrame::OnSocketEvent(wxSocketEvent
& event
)
642 wxString s
= _("OnSocketEvent: ");
644 switch(event
.GetSocketEvent())
646 case wxSOCKET_INPUT
: s
.Append(_("wxSOCKET_INPUT\n")); break;
647 case wxSOCKET_LOST
: s
.Append(_("wxSOCKET_LOST\n")); break;
648 case wxSOCKET_CONNECTION
: s
.Append(_("wxSOCKET_CONNECTION\n")); break;
649 default : s
.Append(_("Unexpected event !\n")); break;
652 m_text
->AppendText(s
);
656 // convenience functions
658 void MyFrame::UpdateStatusBar()
662 if (!m_sock
->IsConnected())
664 s
.Printf(_("Not connected"));
674 m_sock
->GetPeer(addr
);
675 s
.Printf(_("%s : %d"), (addr
.Hostname()).c_str(), addr
.Service());
680 #endif // wxUSE_STATUSBAR
682 m_menuSocket
->Enable(CLIENT_OPEN
, !m_sock
->IsConnected() && !m_busy
);
684 m_menuSocket
->Enable(CLIENT_OPENIPV6
, !m_sock
->IsConnected() && !m_busy
);
686 m_menuSocket
->Enable(CLIENT_TEST1
, m_sock
->IsConnected() && !m_busy
);
687 m_menuSocket
->Enable(CLIENT_TEST2
, m_sock
->IsConnected() && !m_busy
);
688 m_menuSocket
->Enable(CLIENT_TEST3
, m_sock
->IsConnected() && !m_busy
);
689 m_menuSocket
->Enable(CLIENT_CLOSE
, m_sock
->IsConnected());