forked from lizhenghn123/CppLanguagePrograms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTcpClient.cpp
More file actions
91 lines (77 loc) · 2.31 KB
/
TcpClient.cpp
File metadata and controls
91 lines (77 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include "net/TcpClient.h"
#include "net/EventLoop.h"
#include "net/InetAddress.h"
#include "net/TcpConnection.h"
#include "net/TcpConnector.h"
#include "net/SocketUtil.h"
#include "base/Logger.h"
using namespace zl::base;
NAMESPACE_ZL_NET_START
namespace detail
{
void removeConnection(EventLoop *loop, const TcpConnectionPtr& conn)
{
loop->queueInLoop(std::bind(&TcpConnection::connectDestroyed, conn));
}
void removeConnector(TcpConnectorPtr connector)
{
Safe_Delete(connector);
}
}
TcpClient::TcpClient(EventLoop *loop, const InetAddress& serverAddr, const std::string& clientname)
: loop_(loop),
connectionCallback_(defaultConnectionCallback),
messageCallback_(defaultMessageCallback),
retry_(false),
connect_(true),
clientName_(clientname)
{
connector_ = new TcpConnector(loop, serverAddr);
connector_->setNewConnectionCallback(std::bind(&TcpClient::newConnection, this, std::placeholders::_1));
}
TcpClient::~TcpClient()
{
detail::removeConnection(loop_, connection_);
connector_->stop();
loop_->runInLoop(std::bind(&detail::removeConnector, connector_));
}
void TcpClient::connect()
{
connect_ = true;
connector_->connect();
}
void TcpClient::disconnect()
{
connect_ = false;
if (connection_)
{
connection_->shutdown();
}
}
void TcpClient::stop()
{
connect_ = false;
connector_->stop();
}
void TcpClient::newConnection(int sockfd)
{
LOG_INFO("TcpClient::newConnection [%d]", sockfd);
loop_->assertInLoopThread();
InetAddress peerAddr(SocketUtil::getPeerAddr(sockfd));
InetAddress localAddr(SocketUtil::getLocalAddr(sockfd));
TcpConnectionPtr conn(new TcpConnection(loop_, sockfd, localAddr, peerAddr));
conn->setConnectionCallback(connectionCallback_);
conn->setMessageCallback(messageCallback_);
conn->setWriteCompleteCallback(writeCompleteCallback_);
conn->setCloseCallback(std::bind(&TcpClient::removeConnection, this, std::placeholders::_1));
conn->connectEstablished();
connection_ = conn;
}
void TcpClient::removeConnection(const TcpConnectionPtr& conn)
{
loop_->assertInLoopThread();
assert(loop_ == conn->getLoop());
assert(connection_ == conn);
loop_->queueInLoop(std::bind(&TcpConnection::connectDestroyed, conn));
}
NAMESPACE_ZL_NET_END