#include "net_conn_pool.h"
|
#include "socket_io.h"
|
#include "logger_factory.h"
|
|
NetConnPool::NetConnPool() {
|
int i;
|
maxi = -1;
|
nready = 0 ;
|
for (i = 0; i < OPEN_MAX; i++) {
|
conns[i].fd = -1;
|
conns[i].events = 0;
|
}
|
}
|
|
NetConnPool::~NetConnPool() {
|
int connfd;
|
for (auto map_iter = connectionMap.begin(); map_iter != connectionMap.end(); map_iter++) {
|
connfd = map_iter->second;
|
Close(connfd);
|
}
|
}
|
|
|
int NetConnPool::getConn(const char *host, int port) {
|
std::map<std::string, int>::iterator mapIter;
|
int connfd;
|
int i;
|
char mapKey[ADDRSTRLEN];
|
char portstr[NI_MAXSERV];
|
|
sprintf(mapKey, "%s:%d", host, port);
|
mapIter = connectionMap.find(mapKey);
|
if( mapIter != connectionMap.end()) {
|
connfd = mapIter->second;
|
// printf("hit: %s\n", mapKey);
|
} else {
|
// printf("mis: %s\n", mapKey);
|
sprintf(portstr, "%d", port);
|
// printf("open before: %s\n", mapKey);
|
connfd = open_clientfd(host, portstr);
|
// printf("open after: %s\n", mapKey);
|
if(connfd < 0) {
|
LoggerFactory::getLogger()->error(errno, "NetModSocket::connect %s:%d ", host, port);
|
return -1;
|
}
|
connectionMap.insert({mapKey, connfd});
|
}
|
|
|
for (i = 0; i < OPEN_MAX; i++) { /* Find an available slot */
|
if (conns[i].fd < 0)
|
{
|
/* Add connected descriptor to the req_resp_pool */
|
conns[i].fd = connfd;
|
|
conns[i].events = POLLIN;
|
/* Add the descriptor to descriptor set */
|
break;
|
}
|
}
|
|
if (i > maxi)
|
maxi = i;
|
|
if (i == OPEN_MAX) {
|
/* Couldn't find an empty slot */
|
LoggerFactory::getLogger()->error(errno, "add_client error: Too many clients");
|
return -1;
|
}
|
|
|
return connfd;
|
}
|
|
void NetConnPool::putConn(int connfd) {
|
int i;
|
for (i = 0; i <= maxi; i++) {
|
if(conns[i].fd == connfd) {
|
conns[i].fd = -1;
|
}
|
}
|
}
|
|
void NetConnPool::closeConn(int connfd) {
|
int i;
|
std::map<std::string, int>::iterator map_iter;
|
if(close(connfd) != 0) {
|
LoggerFactory::getLogger()->error(errno, "NetModSocket::close_connect close");
|
}
|
|
|
for (i = 0; i <= maxi; i++) {
|
if(conns[i].fd == connfd) {
|
conns[i].fd = -1;
|
}
|
}
|
|
for ( map_iter = connectionMap.begin(); map_iter != connectionMap.end(); ) {
|
if(connfd == map_iter->second) {
|
// std::cout << "map_iter->first==" << map_iter->first << std::endl;
|
map_iter = connectionMap.erase(map_iter);
|
} else {
|
++map_iter;
|
}
|
}
|
|
// LoggerFactory::getLogger()->debug( "closed %d\n", connfd);
|
|
}
|