wangzhengquan
2020-12-30 5eced9fa401e05226309ec9682df4310b18683c3
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#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);
 
}