BreakInSocket.h
Go to the documentation of this file.
1 #pragma once
2 #include <bzsnet/BufferedSocket.h>
3 #include <bzscore/sync.h>
4 #include <bzscore/thread.h>
5 
6 namespace GDBServerFoundation
7 {
10  {
11  public:
12  virtual void OnBreakInRequest()=0;
13  };
14 
16 
36  {
37  public:
38  enum {kBreakInByte = 0x03};
39 
40  private:
41  BazisLib::Network::TCPSocketEx *m_pSocket;
42 
43  private:
44  BazisLib::MemberThread m_WorkerThread;
45  BazisLib::Mutex m_RecvMutex;
46  BazisLib::Semaphore m_Semaphore;
47  bool m_bTerminating;
48 
49  IBreakInTarget *m_pTarget;
50 
51  private:
52  int WorkerThreadBody()
53  {
54  BazisLib::MutexLocker lck(m_RecvMutex);
55  while (!m_bTerminating)
56  {
57  size_t total = 0;
58  void *pData = m_pSocket->PeekAbs(1, &total);
59  if (!pData || !total || *((char *)pData) == kBreakInByte)
60  {
61  if (total)
62  m_pSocket->Discard(pData, 1);
63 
64  IBreakInTarget *pTarget = m_pTarget;
65  if (pTarget)
66  {
67  m_RecvMutex.Unlock();
68  pTarget->OnBreakInRequest();
69  m_RecvMutex.Lock();
70  }
71 
72  continue;
73  }
74 
75  m_RecvMutex.Unlock();
76  m_Semaphore.Wait();
77  m_RecvMutex.Lock();
78  }
79  return 0;
80  }
81 
82  public:
83  BreakInSocket(BazisLib::Network::TCPSocketEx *pSock)
84  : m_pSocket(pSock)
85  , m_WorkerThread(this, &BreakInSocket::WorkerThreadBody)
86  , m_bTerminating(false)
87  , m_pTarget(NULL)
88  {
89  m_WorkerThread.Start();
90  }
91 
93  {
94  m_bTerminating = true;
95  m_Semaphore.Signal();
96  m_WorkerThread.Join();
97  }
98 
99  size_t Send(const void *pBuffer, size_t size)
100  {
101  return m_pSocket->Send(pBuffer, size);
102  }
103 
104  void SetTarget(IBreakInTarget *pTarget)
105  {
106  m_pTarget = pTarget;
107  }
108 
111  {
112  private:
113  BreakInSocket &m_Socket;
114 
115  public:
117  : m_Socket(sock)
118  {
119  m_Socket.m_RecvMutex.Lock();
120  }
121 
122  BazisLib::Network::TCPSocketEx *operator->()
123  {
124  return m_Socket.m_pSocket;
125  }
126 
128  {
129  m_Socket.m_RecvMutex.Unlock();
130  m_Socket.m_Semaphore.Signal();
131  }
132  };
133  };
134 }