]>
git.saurik.com Git - wxWidgets.git/blob - samples/sockets/client.cpp
8c336ba34e5c507727eec9c86f91b87cbfba4b5d
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
)
304 m_menuSocket
->Enable(CLIENT_OPEN
, false);
306 m_menuSocket
->Enable(CLIENT_OPENIPV6
, false);
308 m_menuSocket
->Enable(CLIENT_CLOSE
, false);
310 // Ask user for server address
311 wxString hostname
= wxGetTextFromUser(
312 _("Enter the address of the wxSocket demo server:"),
316 addr
->Hostname(hostname
);
319 // Mini-tutorial for Connect() :-)
320 // ---------------------------
322 // There are two ways to use Connect(): blocking and non-blocking,
323 // depending on the value passed as the 'wait' (2nd) parameter.
325 // Connect(addr, true) will wait until the connection completes,
326 // returning true on success and false on failure. This call blocks
327 // the GUI (this might be changed in future releases to honour the
328 // wxSOCKET_BLOCK flag).
330 // Connect(addr, false) will issue a nonblocking connection request
331 // and return immediately. If the return value is true, then the
332 // connection has been already successfully established. If it is
333 // false, you must wait for the request to complete, either with
334 // WaitOnConnect() or by watching wxSOCKET_CONNECTION / LOST
335 // events (please read the documentation).
337 // WaitOnConnect() itself never blocks the GUI (this might change
338 // in the future to honour the wxSOCKET_BLOCK flag). This call will
339 // return false on timeout, or true if the connection request
340 // completes, which in turn might mean:
342 // a) That the connection was successfully established
343 // b) That the connection request failed (for example, because
344 // it was refused by the peer.
346 // Use IsConnected() to distinguish between these two.
348 // So, in a brief, you should do one of the following things:
350 // For blocking Connect:
352 // bool success = client->Connect(addr, true);
354 // For nonblocking Connect:
356 // client->Connect(addr, false);
358 // bool waitmore = true;
359 // while (! client->WaitOnConnect(seconds, millis) && waitmore )
361 // // possibly give some feedback to the user,
362 // // update waitmore if needed.
364 // bool success = client->IsConnected();
366 // And that's all :-)
368 m_text
->AppendText(_("\nTrying to connect (timeout = 10 sec) ...\n"));
369 m_sock
->Connect(*addr
, false);
370 m_sock
->WaitOnConnect(10);
372 if (m_sock
->IsConnected())
373 m_text
->AppendText(_("Succeeded ! Connection established\n"));
377 m_text
->AppendText(_("Failed ! Unable to connect\n"));
378 wxMessageBox(_("Can't connect to the specified host"), _("Alert !"));
384 void MyFrame::OnTest1(wxCommandEvent
& WXUNUSED(event
))
386 // Disable socket menu entries (exception: Close Session)
390 m_text
->AppendText(_("\n=== Test 1 begins ===\n"));
392 // Tell the server which test we are running
393 unsigned char c
= 0xBE;
394 m_sock
->Write(&c
, 1);
396 // Send some data and read it back. We know the size of the
397 // buffer, so we can specify the exact number of bytes to be
398 // sent or received and use the wxSOCKET_WAITALL flag. Also,
399 // we have disabled menu entries which could interfere with
400 // the test, so we can safely avoid the wxSOCKET_BLOCK flag.
402 // First we send a byte with the length of the string, then
403 // we send the string itself (do NOT try to send any integral
404 // value larger than a byte "as is" across the network, or
405 // you might be in trouble! Ever heard about big and little
406 // endian computers?)
408 m_sock
->SetFlags(wxSOCKET_WAITALL
);
410 const wxChar
*buf1
= _T("Test string (less than 256 chars!)");
411 unsigned char len
= (unsigned char)((wxStrlen(buf1
) + 1)*sizeof(wxChar
));
412 wxChar
*buf2
= new wxChar
[wxStrlen(buf1
) + 1];
414 m_text
->AppendText(_("Sending a test buffer to the server ..."));
415 m_sock
->Write(&len
, 1);
416 m_sock
->Write(buf1
, len
);
417 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
419 m_text
->AppendText(_("Receiving the buffer back from server ..."));
420 m_sock
->Read(buf2
, len
);
421 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
423 m_text
->AppendText(_("Comparing the two buffers ..."));
424 if (memcmp(buf1
, buf2
, len
) != 0)
426 m_text
->AppendText(_("failed!\n"));
427 m_text
->AppendText(_("Test 1 failed !\n"));
431 m_text
->AppendText(_("done\n"));
432 m_text
->AppendText(_("Test 1 passed !\n"));
434 m_text
->AppendText(_("=== Test 1 ends ===\n"));
441 void MyFrame::OnTest2(wxCommandEvent
& WXUNUSED(event
))
447 // Disable socket menu entries (exception: Close Session)
451 m_text
->AppendText(_("\n=== Test 2 begins ===\n"));
453 // Tell the server which test we are running
454 unsigned char c
= 0xCE;
455 m_sock
->Write(&c
, 1);
457 // Here we use ReadMsg and WriteMsg to send messages with
458 // a header with size information. Also, the reception is
459 // event triggered, so we test input events as well.
461 // We need to set no flags here (ReadMsg and WriteMsg are
462 // not affected by flags)
464 m_sock
->SetFlags(wxSOCKET_WAITALL
);
466 wxString s
= wxGetTextFromUser(
467 _("Enter an arbitrary string to send to the server:"),
469 _("Yes I like wxWidgets!"));
472 len
= (wxStrlen(msg1
) + 1) * sizeof(wxChar
);
473 msg2
= new wxChar
[wxStrlen(msg1
) + 1];
475 m_text
->AppendText(_("Sending the string with WriteMsg ..."));
476 m_sock
->WriteMsg(msg1
, len
);
477 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
478 m_text
->AppendText(_("Waiting for an event (timeout = 2 sec)\n"));
480 // Wait until data available (will also return if the connection is lost)
481 m_sock
->WaitForRead(2);
483 if (m_sock
->IsData())
485 m_text
->AppendText(_("Reading the string back with ReadMsg ..."));
486 m_sock
->ReadMsg(msg2
, len
);
487 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
488 m_text
->AppendText(_("Comparing the two buffers ..."));
489 if (memcmp(msg1
, msg2
, len
) != 0)
491 m_text
->AppendText(_("failed!\n"));
492 m_text
->AppendText(_("Test 2 failed !\n"));
496 m_text
->AppendText(_("done\n"));
497 m_text
->AppendText(_("Test 2 passed !\n"));
501 m_text
->AppendText(_("Timeout ! Test 2 failed.\n"));
503 m_text
->AppendText(_("=== Test 2 ends ===\n"));
510 void MyFrame::OnTest3(wxCommandEvent
& WXUNUSED(event
))
516 // Disable socket menu entries (exception: Close Session)
520 m_text
->AppendText(_("\n=== Test 3 begins ===\n"));
522 // Tell the server which test we are running
523 unsigned char c
= 0xDE;
524 m_sock
->Write(&c
, 1);
526 // This test also is similar to the first one but it sends a
527 // large buffer so that wxSocket is actually forced to split
528 // it into pieces and take care of sending everything before
531 m_sock
->SetFlags(wxSOCKET_WAITALL
);
533 // Note that len is in kbytes here!
535 buf1
= new char[len
* 1024];
536 buf2
= new char[len
* 1024];
538 for (int i
= 0; i
< len
* 1024; i
++)
539 buf1
[i
] = (char)(i
% 256);
541 m_text
->AppendText(_("Sending a large buffer (32K) to the server ..."));
542 m_sock
->Write(&len
, 1);
543 m_sock
->Write(buf1
, len
* 1024);
544 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
546 m_text
->AppendText(_("Receiving the buffer back from server ..."));
547 m_sock
->Read(buf2
, len
* 1024);
548 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
550 m_text
->AppendText(_("Comparing the two buffers ..."));
551 if (memcmp(buf1
, buf2
, len
) != 0)
553 m_text
->AppendText(_("failed!\n"));
554 m_text
->AppendText(_("Test 3 failed !\n"));
558 m_text
->AppendText(_("done\n"));
559 m_text
->AppendText(_("Test 3 passed !\n"));
561 m_text
->AppendText(_("=== Test 3 ends ===\n"));
568 void MyFrame::OnCloseConnection(wxCommandEvent
& WXUNUSED(event
))
574 void MyFrame::OnDatagram(wxCommandEvent
& WXUNUSED(event
))
576 m_text
->AppendText(_("\n=== Datagram test begins ===\n"));
577 m_text
->AppendText(_("Sorry, not implemented\n"));
578 m_text
->AppendText(_("=== Datagram test ends ===\n"));
583 void MyFrame::OnTestURL(wxCommandEvent
& WXUNUSED(event
))
585 // Note that we are creating a new socket here, so this
586 // won't mess with the client/server demo.
589 m_text
->AppendText(_("\n=== URL test begins ===\n"));
590 wxString urlname
= wxGetTextFromUser(_("Enter an URL to get"),
592 _T("http://localhost"));
596 if (url
.GetError() != wxURL_NOERR
)
598 m_text
->AppendText(_("Error: couldn't parse URL\n"));
599 m_text
->AppendText(_("=== URL test ends ===\n"));
603 // Try to get the input stream (connects to the given URL)
604 m_text
->AppendText(_("Trying to establish connection...\n"));
606 wxInputStream
*data
= url
.GetInputStream();
609 m_text
->AppendText(_("Error: couldn't read from URL\n"));
610 m_text
->AppendText(_("=== URL test ends ===\n"));
614 // Print the contents type and file size
616 s
.Printf(_("Contents type: %s\nFile size: %i\nStarting to download...\n"),
617 url
.GetProtocol().GetContentType().c_str(),
619 m_text
->AppendText(s
);
623 wxFile
fileTest(wxT("test.url"), wxFile::write
);
624 wxFileOutputStream
sout(fileTest
);
627 m_text
->AppendText(_("Error: couldn't open file for output\n"));
628 m_text
->AppendText(_("=== URL test ends ===\n"));
633 m_text
->AppendText(_("Results written to file: test.url\n"));
634 m_text
->AppendText(_("Done.\n"));
635 m_text
->AppendText(_("=== URL test ends ===\n"));
642 void MyFrame::OnSocketEvent(wxSocketEvent
& event
)
644 wxString s
= _("OnSocketEvent: ");
646 switch(event
.GetSocketEvent())
648 case wxSOCKET_INPUT
: s
.Append(_("wxSOCKET_INPUT\n")); break;
649 case wxSOCKET_LOST
: s
.Append(_("wxSOCKET_LOST\n")); break;
650 case wxSOCKET_CONNECTION
: s
.Append(_("wxSOCKET_CONNECTION\n")); break;
651 default : s
.Append(_("Unexpected event !\n")); break;
654 m_text
->AppendText(s
);
658 // convenience functions
660 void MyFrame::UpdateStatusBar()
664 if (!m_sock
->IsConnected())
666 s
.Printf(_("Not connected"));
676 m_sock
->GetPeer(addr
);
677 s
.Printf(_("%s : %d"), (addr
.Hostname()).c_str(), addr
.Service());
682 #endif // wxUSE_STATUSBAR
684 m_menuSocket
->Enable(CLIENT_OPEN
, !m_sock
->IsConnected() && !m_busy
);
686 m_menuSocket
->Enable(CLIENT_OPENIPV6
, !m_sock
->IsConnected() && !m_busy
);
688 m_menuSocket
->Enable(CLIENT_TEST1
, m_sock
->IsConnected() && !m_busy
);
689 m_menuSocket
->Enable(CLIENT_TEST2
, m_sock
->IsConnected() && !m_busy
);
690 m_menuSocket
->Enable(CLIENT_TEST3
, m_sock
->IsConnected() && !m_busy
);
691 m_menuSocket
->Enable(CLIENT_CLOSE
, m_sock
->IsConnected());