]>
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 // Create the main application window
158 MyFrame
*frame
= new MyFrame();
160 // Show it and tell the application that it's our main window
168 // --------------------------------------------------------------------------
170 // --------------------------------------------------------------------------
173 MyFrame::MyFrame() : wxFrame((wxFrame
*)NULL
, wxID_ANY
,
174 _("wxSocket demo: Client"),
175 wxDefaultPosition
, wxSize(300, 200))
177 // Give the frame an icon
178 SetIcon(wxICON(mondrian
));
181 m_menuFile
= new wxMenu();
182 m_menuFile
->Append(CLIENT_ABOUT
, _("&About...\tCtrl-A"), _("Show about dialog"));
183 m_menuFile
->AppendSeparator();
184 m_menuFile
->Append(CLIENT_QUIT
, _("E&xit\tAlt-X"), _("Quit client"));
186 m_menuSocket
= new wxMenu();
187 m_menuSocket
->Append(CLIENT_OPEN
, _("&Open session"), _("Connect to server"));
188 m_menuSocket
->AppendSeparator();
189 m_menuSocket
->Append(CLIENT_TEST1
, _("Test &1"), _("Test basic functionality"));
190 m_menuSocket
->Append(CLIENT_TEST2
, _("Test &2"), _("Test ReadMsg and WriteMsg"));
191 m_menuSocket
->Append(CLIENT_TEST3
, _("Test &3"), _("Test large data transfer"));
192 m_menuSocket
->AppendSeparator();
193 m_menuSocket
->Append(CLIENT_CLOSE
, _("&Close session"), _("Close connection"));
195 m_menuDatagramSocket
= new wxMenu();
196 m_menuDatagramSocket
->Append(CLIENT_DGRAM
, _("Send Datagram"), _("Test UDP sockets"));
199 m_menuProtocols
= new wxMenu();
200 m_menuProtocols
->Append(CLIENT_TESTURL
, _("Test URL"), _("Get data from the specified URL"));
203 // Append menus to the menubar
204 m_menuBar
= new wxMenuBar();
205 m_menuBar
->Append(m_menuFile
, _("&File"));
206 m_menuBar
->Append(m_menuSocket
, _("&SocketClient"));
207 m_menuBar
->Append(m_menuDatagramSocket
, _("&DatagramSocket"));
209 m_menuBar
->Append(m_menuProtocols
, _("&Protocols"));
211 SetMenuBar(m_menuBar
);
216 #endif // wxUSE_STATUSBAR
218 // Make a textctrl for logging
219 m_text
= new wxTextCtrl(this, wxID_ANY
,
220 _("Welcome to wxSocket demo: Client\nClient ready\n"),
221 wxDefaultPosition
, wxDefaultSize
,
222 wxTE_MULTILINE
| wxTE_READONLY
);
225 m_sock
= new wxSocketClient();
227 // Setup the event handler and subscribe to most events
228 m_sock
->SetEventHandler(*this, SOCKET_ID
);
229 m_sock
->SetNotify(wxSOCKET_CONNECTION_FLAG
|
230 wxSOCKET_INPUT_FLAG
|
232 m_sock
->Notify(true);
240 // No delayed deletion here, as the frame is dying anyway
246 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
248 // true is to force the frame to close
252 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
254 wxMessageBox(_("wxSocket demo: Client\n(c) 1999 Guillermo Rodriguez Garcia\n"),
256 wxOK
| wxICON_INFORMATION
, this);
259 void MyFrame::OnOpenConnection(wxCommandEvent
& WXUNUSED(event
))
263 m_menuSocket
->Enable(CLIENT_OPEN
, false);
264 m_menuSocket
->Enable(CLIENT_CLOSE
, false);
266 // Ask user for server address
267 wxString hostname
= wxGetTextFromUser(
268 _("Enter the address of the wxSocket demo server:"),
272 addr
.Hostname(hostname
);
275 // Mini-tutorial for Connect() :-)
276 // ---------------------------
278 // There are two ways to use Connect(): blocking and non-blocking,
279 // depending on the value passed as the 'wait' (2nd) parameter.
281 // Connect(addr, true) will wait until the connection completes,
282 // returning true on success and false on failure. This call blocks
283 // the GUI (this might be changed in future releases to honour the
284 // wxSOCKET_BLOCK flag).
286 // Connect(addr, false) will issue a nonblocking connection request
287 // and return immediately. If the return value is true, then the
288 // connection has been already successfully established. If it is
289 // false, you must wait for the request to complete, either with
290 // WaitOnConnect() or by watching wxSOCKET_CONNECTION / LOST
291 // events (please read the documentation).
293 // WaitOnConnect() itself never blocks the GUI (this might change
294 // in the future to honour the wxSOCKET_BLOCK flag). This call will
295 // return false on timeout, or true if the connection request
296 // completes, which in turn might mean:
298 // a) That the connection was successfully established
299 // b) That the connection request failed (for example, because
300 // it was refused by the peer.
302 // Use IsConnected() to distinguish between these two.
304 // So, in a brief, you should do one of the following things:
306 // For blocking Connect:
308 // bool success = client->Connect(addr, true);
310 // For nonblocking Connect:
312 // client->Connect(addr, false);
314 // bool waitmore = true;
315 // while (! client->WaitOnConnect(seconds, millis) && waitmore )
317 // // possibly give some feedback to the user,
318 // // update waitmore if needed.
320 // bool success = client->IsConnected();
322 // And that's all :-)
324 m_text
->AppendText(_("\nTrying to connect (timeout = 10 sec) ...\n"));
325 m_sock
->Connect(addr
, false);
326 m_sock
->WaitOnConnect(10);
328 if (m_sock
->IsConnected())
329 m_text
->AppendText(_("Succeeded ! Connection established\n"));
333 m_text
->AppendText(_("Failed ! Unable to connect\n"));
334 wxMessageBox(_("Can't connect to the specified host"), _("Alert !"));
340 void MyFrame::OnTest1(wxCommandEvent
& WXUNUSED(event
))
346 // Disable socket menu entries (exception: Close Session)
350 m_text
->AppendText(_("\n=== Test 1 begins ===\n"));
352 // Tell the server which test we are running
353 unsigned char c
= 0xBE;
354 m_sock
->Write(&c
, 1);
356 // Send some data and read it back. We know the size of the
357 // buffer, so we can specify the exact number of bytes to be
358 // sent or received and use the wxSOCKET_WAITALL flag. Also,
359 // we have disabled menu entries which could interfere with
360 // the test, so we can safely avoid the wxSOCKET_BLOCK flag.
362 // First we send a byte with the length of the string, then
363 // we send the string itself (do NOT try to send any integral
364 // value larger than a byte "as is" across the network, or
365 // you might be in trouble! Ever heard about big and little
366 // endian computers?)
368 m_sock
->SetFlags(wxSOCKET_WAITALL
);
370 buf1
= _("Test string (less than 256 chars!)");
371 len
= (unsigned char)((wxStrlen(buf1
) + 1) * sizeof(wxChar
));
372 buf2
= new wxChar
[wxStrlen(buf1
) + 1];
374 m_text
->AppendText(_("Sending a test buffer to the server ..."));
375 m_sock
->Write(&len
, 1);
376 m_sock
->Write(buf1
, len
);
377 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
379 m_text
->AppendText(_("Receiving the buffer back from server ..."));
380 m_sock
->Read(buf2
, len
);
381 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
383 m_text
->AppendText(_("Comparing the two buffers ..."));
384 if (memcmp(buf1
, buf2
, len
) != 0)
386 m_text
->AppendText(_("failed!\n"));
387 m_text
->AppendText(_("Test 1 failed !\n"));
391 m_text
->AppendText(_("done\n"));
392 m_text
->AppendText(_("Test 1 passed !\n"));
394 m_text
->AppendText(_("=== Test 1 ends ===\n"));
401 void MyFrame::OnTest2(wxCommandEvent
& WXUNUSED(event
))
407 // Disable socket menu entries (exception: Close Session)
411 m_text
->AppendText(_("\n=== Test 2 begins ===\n"));
413 // Tell the server which test we are running
414 unsigned char c
= 0xCE;
415 m_sock
->Write(&c
, 1);
417 // Here we use ReadMsg and WriteMsg to send messages with
418 // a header with size information. Also, the reception is
419 // event triggered, so we test input events as well.
421 // We need to set no flags here (ReadMsg and WriteMsg are
422 // not affected by flags)
424 m_sock
->SetFlags(wxSOCKET_WAITALL
);
426 wxString s
= wxGetTextFromUser(
427 _("Enter an arbitrary string to send to the server:"),
429 _("Yes I like wxWidgets!"));
432 len
= (wxStrlen(msg1
) + 1) * sizeof(wxChar
);
433 msg2
= new wxChar
[wxStrlen(msg1
) + 1];
435 m_text
->AppendText(_("Sending the string with WriteMsg ..."));
436 m_sock
->WriteMsg(msg1
, len
);
437 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
438 m_text
->AppendText(_("Waiting for an event (timeout = 2 sec)\n"));
440 // Wait until data available (will also return if the connection is lost)
441 m_sock
->WaitForRead(2);
443 if (m_sock
->IsData())
445 m_text
->AppendText(_("Reading the string back with ReadMsg ..."));
446 m_sock
->ReadMsg(msg2
, len
);
447 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
448 m_text
->AppendText(_("Comparing the two buffers ..."));
449 if (memcmp(msg1
, msg2
, len
) != 0)
451 m_text
->AppendText(_("failed!\n"));
452 m_text
->AppendText(_("Test 2 failed !\n"));
456 m_text
->AppendText(_("done\n"));
457 m_text
->AppendText(_("Test 2 passed !\n"));
461 m_text
->AppendText(_("Timeout ! Test 2 failed.\n"));
463 m_text
->AppendText(_("=== Test 2 ends ===\n"));
470 void MyFrame::OnTest3(wxCommandEvent
& WXUNUSED(event
))
476 // Disable socket menu entries (exception: Close Session)
480 m_text
->AppendText(_("\n=== Test 3 begins ===\n"));
482 // Tell the server which test we are running
483 unsigned char c
= 0xDE;
484 m_sock
->Write(&c
, 1);
486 // This test also is similar to the first one but it sends a
487 // large buffer so that wxSocket is actually forced to split
488 // it into pieces and take care of sending everything before
491 m_sock
->SetFlags(wxSOCKET_WAITALL
);
493 // Note that len is in kbytes here!
495 buf1
= new char[len
* 1024];
496 buf2
= new char[len
* 1024];
498 for (int i
= 0; i
< len
* 1024; i
++)
499 buf1
[i
] = (char)(i
% 256);
501 m_text
->AppendText(_("Sending a large buffer (32K) to the server ..."));
502 m_sock
->Write(&len
, 1);
503 m_sock
->Write(buf1
, len
* 1024);
504 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
506 m_text
->AppendText(_("Receiving the buffer back from server ..."));
507 m_sock
->Read(buf2
, len
* 1024);
508 m_text
->AppendText(m_sock
->Error() ? _("failed !\n") : _("done\n"));
510 m_text
->AppendText(_("Comparing the two buffers ..."));
511 if (memcmp(buf1
, buf2
, len
) != 0)
513 m_text
->AppendText(_("failed!\n"));
514 m_text
->AppendText(_("Test 3 failed !\n"));
518 m_text
->AppendText(_("done\n"));
519 m_text
->AppendText(_("Test 3 passed !\n"));
521 m_text
->AppendText(_("=== Test 3 ends ===\n"));
528 void MyFrame::OnCloseConnection(wxCommandEvent
& WXUNUSED(event
))
534 void MyFrame::OnDatagram(wxCommandEvent
& WXUNUSED(event
))
536 m_text
->AppendText(_("\n=== Datagram test begins ===\n"));
537 m_text
->AppendText(_("Sorry, not implemented\n"));
538 m_text
->AppendText(_("=== Datagram test ends ===\n"));
543 void MyFrame::OnTestURL(wxCommandEvent
& WXUNUSED(event
))
545 // Note that we are creating a new socket here, so this
546 // won't mess with the client/server demo.
549 m_text
->AppendText(_("\n=== URL test begins ===\n"));
550 wxString urlname
= wxGetTextFromUser(_("Enter an URL to get"),
552 _T("http://localhost"));
556 if (url
.GetError() != wxURL_NOERR
)
558 m_text
->AppendText(_("Error: couldn't parse URL\n"));
559 m_text
->AppendText(_("=== URL test ends ===\n"));
563 // Try to get the input stream (connects to the given URL)
564 m_text
->AppendText(_("Trying to establish connection...\n"));
566 wxInputStream
*data
= url
.GetInputStream();
569 m_text
->AppendText(_("Error: couldn't read from URL\n"));
570 m_text
->AppendText(_("=== URL test ends ===\n"));
574 // Print the contents type and file size
576 s
.Printf(_("Contents type: %s\nFile size: %i\nStarting to download...\n"),
577 url
.GetProtocol().GetContentType().c_str(),
579 m_text
->AppendText(s
);
583 wxFile
fileTest(wxT("test.url"), wxFile::write
);
584 wxFileOutputStream
sout(fileTest
);
587 m_text
->AppendText(_("Error: couldn't open file for output\n"));
588 m_text
->AppendText(_("=== URL test ends ===\n"));
593 m_text
->AppendText(_("Results written to file: test.url\n"));
594 m_text
->AppendText(_("Done.\n"));
595 m_text
->AppendText(_("=== URL test ends ===\n"));
602 void MyFrame::OnSocketEvent(wxSocketEvent
& event
)
604 wxString s
= _("OnSocketEvent: ");
606 switch(event
.GetSocketEvent())
608 case wxSOCKET_INPUT
: s
.Append(_("wxSOCKET_INPUT\n")); break;
609 case wxSOCKET_LOST
: s
.Append(_("wxSOCKET_LOST\n")); break;
610 case wxSOCKET_CONNECTION
: s
.Append(_("wxSOCKET_CONNECTION\n")); break;
611 default : s
.Append(_("Unexpected event !\n")); break;
614 m_text
->AppendText(s
);
618 // convenience functions
620 void MyFrame::UpdateStatusBar()
624 if (!m_sock
->IsConnected())
626 s
.Printf(_("Not connected"));
632 m_sock
->GetPeer(addr
);
633 s
.Printf(_("%s : %d"), (addr
.Hostname()).c_str(), addr
.Service());
638 #endif // wxUSE_STATUSBAR
640 m_menuSocket
->Enable(CLIENT_OPEN
, !m_sock
->IsConnected() && !m_busy
);
641 m_menuSocket
->Enable(CLIENT_TEST1
, m_sock
->IsConnected() && !m_busy
);
642 m_menuSocket
->Enable(CLIENT_TEST2
, m_sock
->IsConnected() && !m_busy
);
643 m_menuSocket
->Enable(CLIENT_TEST3
, m_sock
->IsConnected() && !m_busy
);
644 m_menuSocket
->Enable(CLIENT_CLOSE
, m_sock
->IsConnected());