forked from chunyi1994/cppevent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcpserver.cpp
81 lines (67 loc) · 1.93 KB
/
tcpserver.cpp
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
#include <algorithm>
#include <signal.h>
#include "tcpserver.h"
#include "event.h"
#include "connection.h"
#include "eventloop.h"
#include "tcp_address.h"
namespace cppevent{
TcpServer::TcpServer(EventLoop *loop, size_t port):
loop_(loop),
port_(port),
listener_(loop, port),
connections_()
{
listener_.setNewConnectionCallback(
std::bind(&TcpServer::newConnection,this,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
}
TcpServer::~TcpServer(){}
void TcpServer::start()
{
log("Server started.");
signal(SIGPIPE, SIG_IGN);
log("Set SIGPIPE ignore");
listener_.listen();
}
void TcpServer::setMessageCallback(const MessageCallback &cb)
{
messageCallback_ = cb;
}
void TcpServer::setConnectionCallback(const ConnectionCallback &cb)
{
connectionCallback_ = cb;
}
void TcpServer::newConnection(int sockfd, sockaddr_in *addr, size_t size)
{
TcpAddress tcpAddr;
tcpAddr.ip_ = inet_ntoa(addr->sin_addr);
tcpAddr.port_ = ntohs(addr->sin_port);
setnonblocking(sockfd);
ConnectionPtr conn = std::make_shared<Connection>(loop_, sockfd);
conn->setAddress(tcpAddr);
conn->setMessageCallback(messageCallback_);
conn->setConnectionCallback(std::bind(&TcpServer::handleConnection, this, std::placeholders::_1));
conn->setConnectionStatus(STATUS_CONNECTING);
connections_[sockfd] = conn;
handleConnection(conn);
}
void connKeep(ConnectionPtr conn)
{
}
void TcpServer::handleConnection(const ConnectionPtr& conn)
{
if(connectionCallback_)
{
connectionCallback_(conn);
}
if(!conn->connecting())
{
//让这个conn指针被std::bind保存一份, 可以让他的生命周期延长到下一次的loop开始
loop_->addTask(std::bind(connKeep, conn));
auto iter = connections_.find(conn->fd());
assert(iter != connections_.end());
connections_.erase(iter);
}
}
}