]>
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 // event handlers for DatagramSocket menu (stub)
80 void OnDatagram(wxCommandEvent
& event
);
82 // socket event handler
83 void OnSocketEvent(wxSocketEvent
& event
);
85 // convenience functions
86 void UpdateStatusBar();
89 wxSocketClient
*m_sock
;
93 wxMenu
*m_menuDatagramSocket
;
94 wxMenu
*m_menuProtocols
;
98 // any class wishing to process wxWidgets events must use this macro
102 // --------------------------------------------------------------------------
104 // --------------------------------------------------------------------------
106 // IDs for the controls and the menu commands
110 CLIENT_QUIT
= wxID_EXIT
,
111 CLIENT_ABOUT
= wxID_ABOUT
,
126 // --------------------------------------------------------------------------
127 // event tables and other macros for wxWidgets
128 // --------------------------------------------------------------------------
130 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
131 EVT_MENU(CLIENT_QUIT
, MyFrame::OnQuit
)
132 EVT_MENU(CLIENT_ABOUT
, MyFrame::OnAbout
)
133 EVT_MENU(CLIENT_OPEN
, MyFrame::OnOpenConnection
)
134 EVT_MENU(CLIENT_TEST1
, MyFrame::OnTest1
)
135 EVT_MENU(CLIENT_TEST2
, MyFrame::OnTest2
)
136 EVT_MENU(CLIENT_TEST3
, MyFrame::OnTest3
)
137 EVT_MENU(CLIENT_CLOSE
, MyFrame::OnCloseConnection
)
138 EVT_MENU(CLIENT_DGRAM
, MyFrame::OnDatagram
)
140 EVT_MENU(CLIENT_TESTURL
, MyFrame::OnTestURL
)
142 EVT_SOCKET(SOCKET_ID
, MyFrame::OnSocketEvent
)
147 // ==========================================================================
149 // ==========================================================================
151 // --------------------------------------------------------------------------
152 // the application class
153 // --------------------------------------------------------------------------
157 if ( !wxApp::OnInit() )
160 // Create the main application window
161 MyFrame
*frame
= new MyFrame();
163 // Show it and tell the application that it's our main window
171 // --------------------------------------------------------------------------
173 // --------------------------------------------------------------------------
176 MyFrame::MyFrame() : wxFrame((wxFrame
*)NULL
, wxID_ANY
,
177 _("wxSocket demo: Client"),
178 wxDefaultPosition
, wxSize(300, 200))
180 // Give the frame an icon
181 SetIcon(wxICON(mondrian
));
184 m_menuFile
= new wxMenu();
185 m_menuFile
->Append(CLIENT_ABOUT
, _("&About...\tCtrl-A"), _("Show about dialog"));
186 m_menuFile
->AppendSeparator();
187 m_menuFile
->Append(CLIENT_QUIT
, _("E&xit\tAlt-X"), _("Quit client"));
189 m_menuSocket
= new wxMenu();
190 m_menuSocket
->Append(CLIENT_OPEN
, _("&Open session"), _("Connect to server"));
191 m_menuSocket
->AppendSeparator();
192 m_menuSocket
->Append(CLIENT_TEST1
, _("Test &1"), _("Test basic functionality"));
193 m_menuSocket
->Append(CLIENT_TEST2
, _("Test &2"), _("Test ReadMsg and WriteMsg"));
194 m_menuSocket
->Append(CLIENT_TEST3
, _("Test &3"), _("Test large data transfer"));
195 m_menuSocket
->AppendSeparator();
196 m_menuSocket
->Append(CLIENT_CLOSE
, _("&Close session"), _("Close connection"));
198 m_menuDatagramSocket
= new wxMenu();
199 m_menuDatagramSocket
->Append(CLIENT_DGRAM
, _("Send Datagram"), _("Test UDP sockets"));
202 m_menuProtocols
= new wxMenu();
203 m_menuProtocols
->Append(CLIENT_TESTURL
, _("Test URL"), _("Get data from the specified URL"));
206 // Append menus to the menubar
207 m_menuBar
= new wxMenuBar();
208 m_menuBar
->Append(m_menuFile
, _("&File"));
209 m_menuBar
->Append(m_menuSocket
, _("&SocketClient"));
210 m_menuBar
->Append(m_menuDatagramSocket
, _("&DatagramSocket"));
212 m_menuBar
->Append(m_menuProtocols
, _("&Protocols"));
214 SetMenuBar(m_menuBar
);
219 #endif // wxUSE_STATUSBAR
221 // Make a textctrl for logging
222 m_text
= new wxTextCtrl(this, wxID_ANY
,
223 _("Welcome to wxSocket demo: Client\nClient ready\n"),
224 wxDefaultPosition
, wxDefaultSize
,
225 wxTE_MULTILINE
| wxTE_READONLY
);
228 m_sock
= new wxSocketClient();
230 // Setup the event handler and subscribe to most events
231 m_sock
->SetEventHandler(*this, SOCKET_ID
);
232 m_sock
->SetNotify(wxSOCKET_CONNECTION_FLAG
|
233 wxSOCKET_INPUT_FLAG
|
235 m_sock
->Notify(true);
243 // No delayed deletion here, as the frame is dying anyway
249 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
251 // true is to force the frame to close
255 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
257 wxMessageBox(_("wxSocket demo: Client\n(c) 1999 Guillermo Rodriguez Garcia\n"),
259 wxOK
| wxICON_INFORMATION
, this);
262 void MyFrame::OnOpenConnection(wxCommandEvent
& WXUNUSED(event
))
266 m_menuSocket
->Enable(CLIENT_OPEN
, false);
267 m_menuSocket
->Enable(CLIENT_CLOSE
, false);
269 // Ask user for server address
270 wxString hostname
= wxGetTextFromUser(
271 _("Enter the address of the wxSocket demo server:"),
275 addr
.Hostname(hostname
);
278 // Mini-tutorial for Connect() :-)
279 // ---------------------------
281 // There are two ways to use Connect(): blocking and non-blocking,
282 // depending on the value passed as the 'wait' (2nd) parameter.
284 // Connect(addr, true) will wait until the connection completes,
285 // returning true on success and false on failure. This call blocks
286 // the GUI (this might be changed in future releases to honour the
287 // wxSOCKET_BLOCK flag).
289 // Connect(addr, false) will issue a nonblocking connection request
290 // and return immediately. If the return value is true, then the
291 // connection has been already successfully established. If it is
292 // false, you must wait for the request to complete, either with
293 // WaitOnConnect() or by watching wxSOCKET_CONNECTION / LOST
294 // events (please read the documentation).
296 // WaitOnConnect() itself never blocks the GUI (this might change
297 // in the future to honour the wxSOCKET_BLOCK flag). This call will
298 // return false on timeout, or true if the connection request
299 // completes, which in turn might mean:
301 // a) That the connection was successfully established
302 // b) That the connection request failed (for example, because
303 // it was refused by the peer.
305 // Use IsConnected() to distinguish between these two.
307 // So, in a brief, you should do one of the following things:
309 // For blocking Connect:
311 // bool success = client->Connect(addr, true);
313 // For nonblocking Connect:
315 // client->Connect(addr, false);
317 // bool waitmore = true;
318 // while (! client->WaitOnConnect(seconds, millis) && waitmore )
320 // // possibly give some feedback to the user,
321 // // update waitmore if needed.
323 // bool success = client->IsConnected();
325 // And that's all :-)
327 m_text
->AppendText(_("\nTrying to connect (timeout = 10 sec) ...\n"));
328 m_sock
->Connect(addr
, false);
329 m_sock
->WaitOnConnect(10);
331 if (m_sock
->IsConnected())
332 m_text
->AppendText(_("Succeeded ! Connection established\n"));
336 m_text
->AppendText(_("Failed ! Unable to connect\n"));
337 wxMessageBox(_("Can't connect to the specified host"), _("Alert !"));
343 void MyFrame::OnTest1(wxCommandEvent
& WXUNUSED(event
))
349 // Disable socket menu entries (exception: Close Session)
353 m_text
->AppendText(_("\n=== Test 1 begins ===\n"));
355 // Tell the server which test we are running
356 unsigned char c
= 0xBE;
357 m_sock
->Write(&c
, 1);
359 // Send some data and read it back. We know the size of the
360 // buffer, so we can specify the exact number of bytes to be
361 // sent or received and use the wxSOCKET_WAITALL flag. Also,
362 // we have disabled menu entries which could interfere with
363 // the test, so we can safely avoid the wxSOCKET_BLOCK flag.
365 // First we send a byte with the length of the string, then
366 // we send the string itself (do NOT try to send any integral
367 // value larger than a byte "as is" across the network, or
368 // you might be in trouble! Ever heard about big and little
369 // endian computers?)
371 m_sock
->SetFlags(wxSOCKET_WAITALL
);
373 buf1
= _("Test string (less than 256 chars!)");
374 len
= (unsigned char)((wxStrlen(buf1
) + 1) * sizeof(wxChar
));
375 buf2
= new wxChar
[wxStrlen(buf1
) + 1];
377 m_text
->AppendText(_("Sending a test buffer to the server ..."));
378 m_sock
->Write(&len
, 1);
379 m_sock
->Write(buf1
, len
);
380 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
382 m_text
->AppendText(_("Receiving the buffer back from server ..."));
383 m_sock
->Read(buf2
, len
);
384 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
386 m_text
->AppendText(_("Comparing the two buffers ..."));
387 if (memcmp(buf1
, buf2
, len
) != 0)
389 m_text
->AppendText(_("failed!\n"));
390 m_text
->AppendText(_("Test 1 failed !\n"));
394 m_text
->AppendText(_("done\n"));
395 m_text
->AppendText(_("Test 1 passed !\n"));
397 m_text
->AppendText(_("=== Test 1 ends ===\n"));
404 void MyFrame::OnTest2(wxCommandEvent
& WXUNUSED(event
))
410 // Disable socket menu entries (exception: Close Session)
414 m_text
->AppendText(_("\n=== Test 2 begins ===\n"));
416 // Tell the server which test we are running
417 unsigned char c
= 0xCE;
418 m_sock
->Write(&c
, 1);
420 // Here we use ReadMsg and WriteMsg to send messages with
421 // a header with size information. Also, the reception is
422 // event triggered, so we test input events as well.
424 // We need to set no flags here (ReadMsg and WriteMsg are
425 // not affected by flags)
427 m_sock
->SetFlags(wxSOCKET_WAITALL
);
429 wxString s
= wxGetTextFromUser(
430 _("Enter an arbitrary string to send to the server:"),
432 _("Yes I like wxWidgets!"));
435 len
= (wxStrlen(msg1
) + 1) * sizeof(wxChar
);
436 msg2
= new wxChar
[wxStrlen(msg1
) + 1];
438 m_text
->AppendText(_("Sending the string with WriteMsg ..."));
439 m_sock
->WriteMsg(msg1
, len
);
440 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
441 m_text
->AppendText(_("Waiting for an event (timeout = 2 sec)\n"));
443 // Wait until data available (will also return if the connection is lost)
444 m_sock
->WaitForRead(2);
446 if (m_sock
->IsData())
448 m_text
->AppendText(_("Reading the string back with ReadMsg ..."));
449 m_sock
->ReadMsg(msg2
, len
);
450 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
451 m_text
->AppendText(_("Comparing the two buffers ..."));
452 if (memcmp(msg1
, msg2
, len
) != 0)
454 m_text
->AppendText(_("failed!\n"));
455 m_text
->AppendText(_("Test 2 failed !\n"));
459 m_text
->AppendText(_("done\n"));
460 m_text
->AppendText(_("Test 2 passed !\n"));
464 m_text
->AppendText(_("Timeout ! Test 2 failed.\n"));
466 m_text
->AppendText(_("=== Test 2 ends ===\n"));
473 void MyFrame::OnTest3(wxCommandEvent
& WXUNUSED(event
))
479 // Disable socket menu entries (exception: Close Session)
483 m_text
->AppendText(_("\n=== Test 3 begins ===\n"));
485 // Tell the server which test we are running
486 unsigned char c
= 0xDE;
487 m_sock
->Write(&c
, 1);
489 // This test also is similar to the first one but it sends a
490 // large buffer so that wxSocket is actually forced to split
491 // it into pieces and take care of sending everything before
494 m_sock
->SetFlags(wxSOCKET_WAITALL
);
496 // Note that len is in kbytes here!
498 buf1
= new char[len
* 1024];
499 buf2
= new char[len
* 1024];
501 for (int i
= 0; i
< len
* 1024; i
++)
502 buf1
[i
] = (char)(i
% 256);
504 m_text
->AppendText(_("Sending a large buffer (32K) to the server ..."));
505 m_sock
->Write(&len
, 1);
506 m_sock
->Write(buf1
, len
* 1024);
507 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
509 m_text
->AppendText(_("Receiving the buffer back from server ..."));
510 m_sock
->Read(buf2
, len
* 1024);
511 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
513 m_text
->AppendText(_("Comparing the two buffers ..."));
514 if (memcmp(buf1
, buf2
, len
) != 0)
516 m_text
->AppendText(_("failed!\n"));
517 m_text
->AppendText(_("Test 3 failed !\n"));
521 m_text
->AppendText(_("done\n"));
522 m_text
->AppendText(_("Test 3 passed !\n"));
524 m_text
->AppendText(_("=== Test 3 ends ===\n"));
531 void MyFrame::OnCloseConnection(wxCommandEvent
& WXUNUSED(event
))
537 void MyFrame::OnDatagram(wxCommandEvent
& WXUNUSED(event
))
539 m_text
->AppendText(_("\n=== Datagram test begins ===\n"));
540 m_text
->AppendText(_("Sorry, not implemented\n"));
541 m_text
->AppendText(_("=== Datagram test ends ===\n"));
546 void MyFrame::OnTestURL(wxCommandEvent
& WXUNUSED(event
))
548 // Note that we are creating a new socket here, so this
549 // won't mess with the client/server demo.
552 m_text
->AppendText(_("\n=== URL test begins ===\n"));
553 wxString urlname
= wxGetTextFromUser(_("Enter an URL to get"),
555 _T("http://localhost"));
559 if (url
.GetError() != wxURL_NOERR
)
561 m_text
->AppendText(_("Error: couldn't parse URL\n"));
562 m_text
->AppendText(_("=== URL test ends ===\n"));
566 // Try to get the input stream (connects to the given URL)
567 m_text
->AppendText(_("Trying to establish connection...\n"));
569 wxInputStream
*data
= url
.GetInputStream();
572 m_text
->AppendText(_("Error: couldn't read from URL\n"));
573 m_text
->AppendText(_("=== URL test ends ===\n"));
577 // Print the contents type and file size
579 s
.Printf(_("Contents type: %s\nFile size: %i\nStarting to download...\n"),
580 url
.GetProtocol().GetContentType().c_str(),
582 m_text
->AppendText(s
);
586 wxFile
fileTest(wxT("test.url"), wxFile::write
);
587 wxFileOutputStream
sout(fileTest
);
590 m_text
->AppendText(_("Error: couldn't open file for output\n"));
591 m_text
->AppendText(_("=== URL test ends ===\n"));
596 m_text
->AppendText(_("Results written to file: test.url\n"));
597 m_text
->AppendText(_("Done.\n"));
598 m_text
->AppendText(_("=== URL test ends ===\n"));
605 void MyFrame::OnSocketEvent(wxSocketEvent
& event
)
607 wxString s
= _("OnSocketEvent: ");
609 switch(event
.GetSocketEvent())
611 case wxSOCKET_INPUT
: s
.Append(_("wxSOCKET_INPUT\n")); break;
612 case wxSOCKET_LOST
: s
.Append(_("wxSOCKET_LOST\n")); break;
613 case wxSOCKET_CONNECTION
: s
.Append(_("wxSOCKET_CONNECTION\n")); break;
614 default : s
.Append(_("Unexpected event !\n")); break;
617 m_text
->AppendText(s
);
621 // convenience functions
623 void MyFrame::UpdateStatusBar()
627 if (!m_sock
->IsConnected())
629 s
.Printf(_("Not connected"));
635 m_sock
->GetPeer(addr
);
636 s
.Printf(_("%s : %d"), (addr
.Hostname()).c_str(), addr
.Service());
641 #endif // wxUSE_STATUSBAR
643 m_menuSocket
->Enable(CLIENT_OPEN
, !m_sock
->IsConnected() && !m_busy
);
644 m_menuSocket
->Enable(CLIENT_TEST1
, m_sock
->IsConnected() && !m_busy
);
645 m_menuSocket
->Enable(CLIENT_TEST2
, m_sock
->IsConnected() && !m_busy
);
646 m_menuSocket
->Enable(CLIENT_TEST3
, m_sock
->IsConnected() && !m_busy
);
647 m_menuSocket
->Enable(CLIENT_CLOSE
, m_sock
->IsConnected());