Ticket #12886: client.cpp

File client.cpp, 1.7 KB (added by chrisstankevitz, 8 years ago)

Example of an application that does not use wxSOCKET_BLOCK that does have disabled events that are subsequently re-enabled by wxSocketReaddGuard::~wxSocketReaddGuard

Line 
1#include "wx/app.h"
2#include "wx/frame.h"
3#include "wx/socket.h"
4#include "wx/timer.h"
5
6class MyApp : public wxApp
7{
8  public:
9    virtual bool OnInit();
10};
11
12class MyFrame : public wxFrame
13{
14  public:
15    MyFrame();
16
17    ~MyFrame();
18
19    void OnTimer(wxTimerEvent& Event);
20
21    // socket event handler
22    void OnSocketEvent(wxSocketEvent& event);
23
24  private:
25    wxSocketClient *m_sock;
26
27    wxTimer* mpTimer;
28
29    DECLARE_EVENT_TABLE()
30};
31
32BEGIN_EVENT_TABLE(MyFrame, wxFrame)
33  EVT_SOCKET(wxID_ANY,     MyFrame::OnSocketEvent)
34  EVT_TIMER(wxID_ANY, MyFrame::OnTimer)
35END_EVENT_TABLE()
36
37IMPLEMENT_APP(MyApp)
38
39bool MyApp::OnInit()
40{
41  if ( !wxApp::OnInit() )
42      return false;
43
44  MyFrame *frame = new MyFrame();
45
46  frame->Show(true);
47
48  return true;
49}
50
51MyFrame::MyFrame() : wxFrame(
52  (wxFrame *)NULL,
53  wxID_ANY,
54  _("wxSocket demo: Client"),
55  wxDefaultPosition,
56  wxSize(300, 200))
57{
58  m_sock = new wxSocketClient();
59
60  m_sock->SetEventHandler(*this);
61
62  m_sock->SetNotify(wxSOCKET_CONNECTION_FLAG | wxSOCKET_LOST_FLAG);
63
64  m_sock->Notify(true);
65
66  wxIPV4address addr;
67
68  addr.Hostname("localhost");
69
70  addr.Service(4040);
71
72  m_sock->Connect(addr, false);
73
74  mpTimer = new wxTimer(this);
75
76  mpTimer->Start(500, false);
77}
78
79MyFrame::~MyFrame()
80{
81  delete m_sock;
82}
83
84void MyFrame::OnTimer(wxTimerEvent& WXUNUSED(event))
85{
86  if (m_sock->IsConnected())
87  {
88    char Buffer[6] = "Hello";
89
90    m_sock->Write(Buffer, 5);
91
92    m_sock->Read(Buffer, 5);
93  }
94}
95
96void MyFrame::OnSocketEvent(wxSocketEvent& event)
97{
98  switch ( event.GetSocketEvent() )
99  {
100    case wxSOCKET_CONNECTION:
101      m_sock->Notify(false);
102      m_sock->SetFlags(wxSOCKET_NOWAIT);
103      break;
104
105    default:
106        break;
107  }
108}