SpiecsEngine
 
Loading...
Searching...
No Matches
TcpConnection.h
Go to the documentation of this file.
1/**
2* @file TcpConnection.h.
3* @brief The TcpConnection Class Definitions.
4* @author Spices & Muduo.
5*/
6
7#pragma once
8#include "Core/Core.h"
9#include "InetAddress.h"
10#include "Buffer.h"
11#include "Callbacks.h"
12
13namespace Spices {
14
15namespace Net {
16
17 class Channel;
18 class EventLoop;
19 class Socket;
20
21 /**
22 * @brief Combine of Socket Connection data.
23 */
25 {
26 public:
27
28 enum class State
29 {
30 Disconnected = 0,
31 Connecting = 1,
32 Connected = 2,
34 };
35
36 public:
37
38 /**
39 * @brief Constructor Function.
40 * @param[in] ioLoop IO EventLoop.
41 * @param[in] name TcpConnection identify.
42 * @param[in] socketFd SOCKET.
43 * @param[in] localAddress InetAddress.
44 * @param[in] peerAddress InetAddress.
45 */
47 EventLoop* ioLoop ,
48 const std::string& name ,
49 SOCKET socketFd ,
50 const InetAddress& localAddress ,
51 const InetAddress& peerAddress
52 );
53
54 /**
55 * @brief Destructor Function.
56 */
57 virtual ~TcpConnection();
58
59 /**
60 * @brief Copy Constructor Function.
61 * @note This Class not allowed copy behaves.
62 */
63 TcpConnection(const TcpConnection&) = delete;
64
65 /**
66 * @brief Copy Assignment Operation.
67 * @note This Class not allowed copy behaves.
68 */
70
71 /**
72 * @brief Get this TcpConnection IO EventLoop.
73 * @return Returns this TcpConnection IO EventLoop.
74 */
75 EventLoop* GetLoop() const { return m_IoLoop; }
76
77 /**
78 * @brief Get this TcpConnection name.
79 * @return Returns this TcpConnection name.
80 */
81 const std::string& GetName() const { return m_Name; }
82
83 /**
84 * @brief Get this TcpConnection LocalAddress.
85 * @return Returns this TcpConnection LocalAddress.
86 */
87 const InetAddress& LocalAddress() const { return m_LocalAddress; }
88
89 /**
90 * @brief Get this TcpConnection PeerAddress.
91 * @return Returns this TcpConnection PeerAddress.
92 */
93 const InetAddress& PeerAddress() const { return m_PeerAddress; }
94
95 /**
96 * @brief Determined if this TcpConnection is connected.
97 * @return Returns true if this TcpConnection is connected.
98 */
99 bool Connected() const { return m_State == State::Connected; }
100
101 /**
102 * @brief Send message to socket.
103 * @param[in] buffer Data.
104 */
105 void Send(const std::string& buffer);
106
107 /**
108 * @brief ShutDown socket.
109 */
110 void ShutDown();
111
112 /**
113 * @brief Set ConnectionCallback.
114 * @param[in] cb DelegateConnectionCallback.
115 */
116 void SetConnectionCallback(const DelegateConnectionCallback& cb)
117 {
118 m_ConnectionCallback = cb;
119 }
120
121 /**
122 * @brief Set MessageCallback.
123 * @param[in] cb DelegateMessageCallback.
124 */
125 void SetMessageCallback(const DelegateMessageCallback& cb)
126 {
127 m_MessageCallback = cb;
128 }
129
130 /**
131 * @brief Set WriteCompleteCallback.
132 * @param[in] cb DelegateWriteCompleteCallback.
133 */
134 void SetWriteCompleteCallback(const DelegateWriteCompleteCallback& cb)
135 {
136 m_WriteCompleteCallback = cb;
137 }
138
139 /**
140 * @brief Set HighWaterMarkCallback.
141 * @param[in] cb DelegateHighWaterMarkCallback.
142 */
143 void SetHighWaterMarkCallback(const DelegateHighWaterMarkCallback& cb)
144 {
146 }
147
148 /**
149 * @brief Set CloseCallback.
150 * @param[in] cb DelegateCloseCallback.
151 */
152 void SetCloseCallback(const DelegateCloseCallback& cb)
153 {
154 m_CloseCallback = cb;
155 }
156
157 void ConnectEstablished();
158 void ConnectDestroyed();
159
160 private:
161
162 void SetState(State state) { m_State = state; }
163
164 /**
165 * @brief Handle Read event.
166 */
167 void HandleRead();
168
169 /**
170 * @brief Handle Write event.
171 */
172 void HandleWrite();
173
174 /**
175 * @brief Handle Close event.
176 */
177 void HandleClose();
178
179 /**
180 * @brief Handle Error event.
181 */
182 void HandleError() const;
183
184 /**
185 * @brief Send message to socket.
186 * @param[in] message Data pointer.
187 * @param[in] len message bytes.
188 */
189 void SendInLoop(const char* message, size_t len);
190
191 /**
192 * @brief ShutDown socket.
193 */
194 void ShutDownInLoop() const;
195
196 private:
197
198 /**
199 * @brief io Loop from TcpServer::NewConnection.
200 */
202
203 /**
204 * @brief TcpConnection name.
205 */
206 std::string m_Name;
207
208 /**
209 * @brief TcpConnection state.
210 */
211 std::atomic<State> m_State;
212
213 /**
214 * @brief TcpConnection socket.
215 */
217
218 /**
219 * @brief TcpConnection channel.
220 */
222
223 /**
224 * @brief TcpConnection LocalAddress.
225 */
227
228 /**
229 * @brief TcpConnection PeerAddress.
230 */
232
233 /**
234 * @brief DelegateConnectionCallback.
235 */
236 DelegateConnectionCallback m_ConnectionCallback;
237
238 /**
239 * @brief DelegateMessageCallback.
240 */
241 DelegateMessageCallback m_MessageCallback;
242
243 /**
244 * @brief DelegateWriteCompleteCallback.
245 */
246 DelegateWriteCompleteCallback m_WriteCompleteCallback;
247
248 /**
249 * @brief DelegateHighWaterMarkCallback.
250 */
251 DelegateHighWaterMarkCallback m_HighWaterMarkCallback;
252
253 /**
254 * @brief DelegateCloseCallback.
255 */
256 DelegateCloseCallback m_CloseCallback;
257
258 /**
259 * @brief Input Buffer.
260 */
262
263 /**
264 * @brief Output Buffer.
265 */
267 };
268
269}
270
271}
#define DELEGATE_ONE_PARAM(name, p0)
Use this macro to instance a Delegate Class. One Parameter Specific.
#define DELEGATE_TWO_PARAM(name, p0, p1)
Use this macro to instance a Delegate Class. Two Parameter Specific.
#define SPICES_PROFILE_ZONE
size_t size()
Get size of Agents.
bool empty()
Determine if this Delegate is empty;.
std::shared_ptr< scl::linked_unordered_map< uint64_t, Agent > > m_Agents
Map of Agent Function Pointer.
bool Bind(std::function< void(Args...)> func)
Bind Function pointer to delegate.
virtual ~Delegate_Basic()=default
Destructor Function.
Delegate_Basic()
Constructor Function.
void Broadcast(Args &&... args)
Execute all function pointer.
bool UnBind(std::function< void(Args...)> func)
UnBind Function pointer from delegate.
Basic Class of Delegate. Instance inherited from it and use delegate feature.
void Listen()
Listen accept socket.
Definition Acceptor.cpp:39
std::shared_ptr< Channel > m_AcceptChannel
Acceptor Channel.
Definition Acceptor.h:92
Socket m_AcceptSocket
Acceptor Socket.
Definition Acceptor.h:87
void HandleRead() const
On Read Event Callback.
Definition Acceptor.cpp:48
Acceptor(const Acceptor &)=delete
Copy Constructor Function.
bool IsListening() const
Determine if this is in listening. @reutrn Returns true if is in listening.
Definition Acceptor.h:68
void SetConnectionCallback(const ConnectionCallback &cb)
Set ConnectionCallback.
Definition Acceptor.h:59
Acceptor(const InetAddress &listenAddress, bool reusePort)
Constructor Function.
Definition Acceptor.cpp:15
ConnectionCallback m_ConnectionCallback
ConnectionCallback.
Definition Acceptor.h:97
bool m_IsListening
Boolean of whether is in listening.
Definition Acceptor.h:102
virtual ~Acceptor()
Destructor Function.
Definition Acceptor.cpp:31
Acceptor & operator=(const Acceptor &)=delete
Copy Assignment Operation.
Wrapper of Channel and Socket, As the entrance of comm.
Definition Acceptor.h:24
Wrapper of readwrite buffer.
Definition Buffer.h:19
~Channel()=default
Destructor Function.
void Update()
Update this Channel state to Poller.
Definition Channel.cpp:48
void SetErrorCallback(EventCallback cb)
Set Error Event Callback.
Definition Channel.h:110
EventCallback m_ReadCallback
Read Event Callback.
Definition Channel.h:259
bool IsReading() const
Determine whether the event is a Read Event.
Definition Channel.h:196
EventLoop * m_Loop
This channel interested EventLoop.
Definition Channel.h:237
void SetWriteCallback(EventCallback cb)
Set Write Event Callback.
Definition Channel.h:92
Channel(const Channel &)=delete
Copy Constructor Function.
Channel(SOCKET fd, EventLoop *loop)
Constructor Function.
Definition Channel.cpp:15
EventCallback m_WriteCallback
Write Event Callback.
Definition Channel.h:264
void SetCloseCallback(EventCallback cb)
Set Close Event Callback.
Definition Channel.h:101
void SetRevents(int revt)
Set this REvents type.
Definition Channel.h:133
void DisableReading()
Disable Read event.
Definition Channel.h:147
void DisableAll()
Disable All event.
Definition Channel.h:174
Channel & operator=(const Channel &)=delete
Copy Assignment Operation.
std::optional< std::weak_ptr< void > > m_Tie
Definition Channel.h:254
int Events() const
Get this Events type.
Definition Channel.h:127
EventCallback m_ErrorCallback
Error Event Callback.
Definition Channel.h:274
void HandleEvent() const
Handle happened events on fd.
Definition Channel.cpp:23
void HandleEventsWithGuard() const
Internal handle happened events on fd.
Definition Channel.cpp:53
void Tie(const std::shared_ptr< void > &obj)
Definition Channel.cpp:38
void EnableWriting()
Enable Write event.
Definition Channel.h:156
SOCKET Fd() const
Get this SOCKET.
Definition Channel.h:121
void SetPollState(PollState state)
Set Poll State.
Definition Channel.h:208
bool IsWriting() const
Determine whether the event is a Write Event.
Definition Channel.h:190
void DisableWriting()
Disable Write event.
Definition Channel.h:165
int m_Revents
Current happened event type.
Definition Channel.h:247
void EnableReading()
Enable Read event.
Definition Channel.h:138
PollState GetPollState() const
Get Poll State.
Definition Channel.h:202
EventFlags m_Events
This SOCKET interested Events type.
Definition Channel.h:242
SOCKET m_Fd
This channel interested SOCKET.
Definition Channel.h:232
EventCallback m_CloseCallback
Close Event Callback.
Definition Channel.h:269
void Remove()
Remove this Channel state from Poller.
Definition Channel.cpp:43
PollState m_PollState
This channel PollState.
Definition Channel.h:252
bool IsNoneEvent() const
Determine whether the event is a None Event.
Definition Channel.h:184
void SetReadCallback(EventCallback cb)
Set Read Event Callback.
Definition Channel.h:83
Wrapper of SOCKET'S Event.
Definition Channel.h:27
ThreadPool of Multiple threading EventLoop.
EventLoopThreadWrapper()
Constructor Function.
Definition EventLoop.h:186
virtual ~EventLoopThreadWrapper()
Destructor Function.
static EventLoop *& GetInst(InetAddress *address=nullptr)
Get EventLoop Instance. @reutrn Returns EventLoop Instance.
EventLoop * instance
This thread EventLoop instance.
Definition EventLoop.h:204
Wrapper of Instance/Delete ThreadCache in thread.
Definition EventLoop.h:180
EventLoop & operator=(const EventLoop &)=delete
Copy Assignment Operation.
void HandleWakeUp()
Handle WakeUp notify by read one byte data.
std::vector< Functor > m_PendingFunctors
Delay functors.
Definition EventLoop.h:168
void DoPendingFunctors()
Execute all pending functors.
std::shared_ptr< Poller > m_Poller
Poller instance.
Definition EventLoop.h:148
std::atomic_bool m_IsCallingPendingFunctors
True if is execute pending functors.
Definition EventLoop.h:138
std::atomic_bool m_IsLooping
True if is in Looping.
Definition EventLoop.h:128
bool HasChannel(Channel *channel) const
Determine if channel is inside poller.
std::mutex m_Mutex
Mutex for PendingFunctors.
Definition EventLoop.h:173
EventLoop(const EventLoop &)=delete
Copy Constructor Function.
std::atomic_bool m_IsQuit
True if is quit from Looping.
Definition EventLoop.h:133
EventLoop(InetAddress *address=nullptr)
Constructor Function.
Definition EventLoop.cpp:22
void WakeUp()
WakeUp a thread, which wait on recv, by sending one byte data.
std::unique_ptr< Channel > m_WeakupChannel
Wakeup Channel.
Definition EventLoop.h:158
void Loop()
Start Event Loop.
Definition EventLoop.cpp:48
bool IsInLoopThread() const
Determine if current thread is in eventloop thread.
Definition EventLoop.h:109
void RunInLoop(Functor cb)
Push functor to pending functors.
Definition EventLoop.cpp:79
~EventLoop()
Destructor Function.
Definition EventLoop.cpp:42
Socket m_WakeupFd
Wakeup Socket.
Definition EventLoop.h:153
DWORD m_ThreadId
Thread's identify, which is running this EventLoop.
Definition EventLoop.h:143
void QueueInLoop(Functor cb)
Execute functor in EventLoop thread.
Definition EventLoop.cpp:91
void UpdateChannel(Channel *channel) const
Update channel state with poller.
void Quit()
Quit from Event Loop.
Definition EventLoop.cpp:69
ChannelList m_ActiveChannels
Channels with events.
Definition EventLoop.h:163
void RemoveChannel(Channel *channel) const
Remove channel from poller.
Wrapper of Poller and wakeup socket to acceptor(SubLoop).
Definition EventLoop.h:28
const Version GetVersion() const
Get Http Version.
Definition HttpRequest.h:89
std::string GetHeader(const std::string &name) const
Get a Header from this HttpRequest.
Http Request body.
Definition HttpRequest.h:18
HttpResponse(bool close)
Constructor Function.
void AppendToBuffer(Buffer *output)
Append this response to Buffer.
bool CloseConnection() const
Get CloseConnection.
HttpServer & operator=(const HttpServer &)=delete
Copy Assignment Operation.
HttpServer(const HttpServer &)=delete
Copy Constructor Function.
void OnRequest(const TcpConnectionPtr &connection, const HttpRequest &request)
HttpCallback m_HttpCallback
Definition HttpServer.h:75
virtual ~HttpServer()=default
Destructor Function.
void OnConnection(const TcpConnectionPtr &connection)
HttpServer(const InetAddress &listenAddress, int idleSeconds, TcpServer::Option option=TcpServer::Option::NoReusePort)
Constructor Function.
void Start(int threadSize) const
Start ThreadPool and call listen on acceptor.
WeakConnectionList m_ConnectionList
Definition HttpServer.h:78
void OnMessage(const TcpConnectionPtr &connection, Buffer *buf)
This class is Wrapper of current socket address.
Definition InetAddress.h:22
Inherit from this and Implement Specific Poller.
Definition Poller.h:25
Socket(const Socket &)=delete
Copy Constructor Function.
void SetReuseAddress(bool on) const
Set socket reuse address option.
Definition Socket.cpp:188
void SetTcpNoDelay(bool on) const
Set socket Tcp no delay option.
Definition Socket.cpp:149
void Connect(InetAddress *connectAddress) const
Connect to socket.
Definition Socket.cpp:62
Socket & operator=(const Socket &)=delete
Copy Assignment Operation.
SOCKET m_SocketFd
This socket fd.
Definition Socket.h:142
void Send(const std::string &data) const
Send data to server.
Definition Socket.cpp:106
SOCKET Accept(InetAddress *peerAddress) const
Accept connection on socket.
Definition Socket.cpp:83
Socket()=default
Constructor Function.
void BindAddress(const InetAddress &localAddress) const
Bind address to socket.
Definition Socket.cpp:36
void Create()
Create Non Blocking Socket.
Definition Socket.cpp:27
virtual ~Socket()
Destructor Function.
Definition Socket.cpp:14
std::string Receive() const
Receive data from server.
Definition Socket.cpp:119
SOCKET Fd()
Get this socket fd.
Definition Socket.h:66
Socket(SOCKET socketFd)
Constructor Function.
Definition Socket.h:30
const SOCKET Fd() const
Get this socket fd.
Definition Socket.h:60
void SetKeepAlive(bool on) const
Set socket keep alive option.
Definition Socket.cpp:175
void SetReusePort(bool on) const
Set socket reuse port option.
Definition Socket.cpp:162
void ShutDownWrite() const
Disable writen in socket.
Definition Socket.cpp:136
void Listen() const
Listen on socket.
Definition Socket.cpp:49
This class is Wrapper of socket.
Definition Socket.h:18
const InetAddress & LocalAddress() const
Get this TcpConnection LocalAddress.
void HandleWrite()
Handle Write event.
void SetWriteCompleteCallback(const DelegateWriteCompleteCallback &cb)
Set WriteCompleteCallback.
std::atomic< State > m_State
TcpConnection state.
DelegateHighWaterMarkCallback m_HighWaterMarkCallback
DelegateHighWaterMarkCallback.
std::unique_ptr< Socket > m_Socket
TcpConnection socket.
void SetMessageCallback(const DelegateMessageCallback &cb)
Set MessageCallback.
TcpConnection & operator=(const TcpConnection &)=delete
Copy Assignment Operation.
InetAddress m_PeerAddress
TcpConnection PeerAddress.
InetAddress m_LocalAddress
TcpConnection LocalAddress.
std::string m_Name
TcpConnection name.
void SetConnectionCallback(const DelegateConnectionCallback &cb)
Set ConnectionCallback.
void HandleClose()
Handle Close event.
TcpConnection(EventLoop *ioLoop, const std::string &name, SOCKET socketFd, const InetAddress &localAddress, const InetAddress &peerAddress)
Constructor Function.
void HandleRead()
Handle Read event.
Buffer m_OutputBuffer
Output Buffer.
DelegateCloseCallback m_CloseCallback
DelegateCloseCallback.
Buffer m_InputBuffer
Input Buffer.
DelegateWriteCompleteCallback m_WriteCompleteCallback
DelegateWriteCompleteCallback.
DelegateMessageCallback m_MessageCallback
DelegateMessageCallback.
void SetCloseCallback(const DelegateCloseCallback &cb)
Set CloseCallback.
DelegateConnectionCallback m_ConnectionCallback
DelegateConnectionCallback.
void SetHighWaterMarkCallback(const DelegateHighWaterMarkCallback &cb)
Set HighWaterMarkCallback.
void HandleError() const
Handle Error event.
std::unique_ptr< Channel > m_Channel
TcpConnection channel.
void SendInLoop(const char *message, size_t len)
Send message to socket.
void SetState(State state)
void Send(const std::string &buffer)
Send message to socket.
const InetAddress & PeerAddress() const
Get this TcpConnection PeerAddress.
bool Connected() const
Determined if this TcpConnection is connected.
EventLoop * GetLoop() const
Get this TcpConnection IO EventLoop.
void ShutDown()
ShutDown socket.
EventLoop * m_IoLoop
io Loop from TcpServer::NewConnection.
TcpConnection(const TcpConnection &)=delete
Copy Constructor Function.
virtual ~TcpConnection()
Destructor Function.
void ShutDownInLoop() const
ShutDown socket.
const std::string & GetName() const
Get this TcpConnection name.
Combine of Socket Connection data.
void SetThreadInitCallback(const ThreadInitCallback &cb)
Set Thread initialize Call back.
Definition TcpServer.h:71
void AddMessageCallback(const DelegateMessageCallback::Agent &cb)
Add Message Call back.
Definition TcpServer.h:89
void Start(int threadSize) const
Start ThreadPool and call listen on acceptor.
Definition TcpServer.cpp:46
std::shared_ptr< EventLoopThreadPool > m_ThreadPool
ThreadPool.
Definition TcpServer.h:145
void NewConnection(SOCKET socketFd, const InetAddress &peerAddress)
Handle New Connection to Acceptor.
Definition TcpServer.cpp:57
void RemoveConnectionInLoop(const TcpConnectionPtr &connection)
Remove a TcpConnection InLoop.
Definition TcpServer.cpp:97
TcpServer(const TcpServer &)=delete
Copy Constructor Function.
ConnectionMap m_Connections
All TcpConnections.
Definition TcpServer.h:175
DelegateWriteCompleteCallback m_WriteCompleteCallback
WriteCompleteCallback.
Definition TcpServer.h:160
void RemoveConnection(const TcpConnectionPtr &connection)
Remove a TcpConnection.
Definition TcpServer.cpp:92
TcpServer(const InetAddress &listenAddress, Option option=Option::NoReusePort)
Constructor Function.
Definition TcpServer.cpp:16
TcpServer & operator=(const TcpServer &)=delete
Copy Assignment Operation.
ThreadInitCallback m_ThreadInitCallback
ThreadInitCallback.
Definition TcpServer.h:165
std::unique_ptr< Acceptor > m_Acceptor
Acceptor.
Definition TcpServer.h:140
std::string m_IpPort
TcpServer Ip and Port.
Definition TcpServer.h:135
void AddConnectionCallback(const DelegateConnectionCallback::Agent &cb)
Add Connection Call back.
Definition TcpServer.h:80
virtual ~TcpServer()
Destructor Function.
Definition TcpServer.cpp:33
DelegateConnectionCallback m_ConnectionCallback
ConnectionCallback.
Definition TcpServer.h:150
int m_NextConnectedId
Next Connection id.
Definition TcpServer.h:170
DelegateMessageCallback m_MessageCallback
MessageCallback.
Definition TcpServer.h:155
void AddWriteCompleteCallback(const DelegateWriteCompleteCallback::Agent &cb)
Add WriteComplete Call back.
Definition TcpServer.h:98
Sample of a TcpServer.
Definition TcpServer.h:29
The container combines hashmap and list together. Used in the case that we want iter a hashmap in ord...