Belle II Software  release-08-01-10
EvtSocketManager.cc
1 /**************************************************************************
2  * basf2 (Belle II Analysis Software Framework) *
3  * Author: The Belle II Collaboration *
4  * *
5  * See git log for contributors and copyright holders. *
6  * This file is licensed under LGPL-3.0, see LICENSE.md. *
7  **************************************************************************/
8 
9 #include <daq/dataflow/EvtSocketManager.h>
10 
11 #include <algorithm>
12 #include <cstring>
13 #include <unistd.h>
14 
15 using namespace Belle2;
16 using namespace std;
17 
18 EvtSocketManager::EvtSocketManager(EvtSocketRecv* evtsock)
19 {
20  SocketRecv* sock = evtsock->sock();
21 
22  FD_ZERO(&m_allset);
23  FD_SET(sock->sock(), &m_allset);
24  m_maxfd = sock->sock();
25  m_recv = evtsock;
26  m_sock = sock->sock();
27 }
28 
29 EvtSocketManager::~EvtSocketManager()
30 {
31 }
32 
33 int EvtSocketManager::examine()
34 {
35  memcpy(&m_rset, &m_allset, sizeof(m_rset));
36  memcpy(&m_wset, &m_allset, sizeof(m_wset));
37  struct timeval timeout;
38  timeout.tv_sec = 0; // 1sec
39  timeout.tv_usec = 1000; // 1msec (in microsec)
40  // printf ( "EvtSocketManager: maxfd = %d, start select...\n", m_maxfd);
41  // int rc = select(m_maxfd+1, &m_rset, &m_wset, NULL, NULL );
42  int rc = select(m_maxfd + 1, &m_rset, &m_wset, NULL, &timeout);
43  // printf ( "EvtSocketManager: select returned with %d\n", rc );
44  if (rc < 0)
45  perror("select");
46  else if (rc == 0) // timeout
47  return -1;
48 
49  if (FD_ISSET(m_sock, &m_rset)) { // New connection request
50  int fd = (m_recv->sock())->accept();
51  m_fd.push_back(fd);
52  FD_SET(fd, &m_allset);
53  if (fd > m_maxfd) m_maxfd = fd;
54  /*
55  struct sockaddr_in peername;
56  socklen_t lname = sizeof (peername);
57  int is = getpeername ( fd[0], (sockaddr*)&peername, &lname );
58  struct hostent* dest = gethostbyaddr (
59  (char*)&peername.sin_addr.s_addr, sizeof(unsigned int),AF_INET );
60  tprintf ( "DQM_server : connected to host = %s (port %d); fd=%d\n",
61  dest->h_name, ntohs(peername.sin_port), fd[0] );
62  */
63  return 0;
64  } else { //
65  return 1;
66  }
67 }
68 
69 vector<int>& EvtSocketManager::connected_socket_list()
70 {
71  return m_fd;
72 }
73 
74 bool EvtSocketManager::connected(int fd, bool wreq)
75 {
76  if (!wreq) {
77  if (FD_ISSET(fd, &m_rset))
78  return true;
79  else
80  return false;
81  } else {
82  if (FD_ISSET(fd, &m_wset))
83  return true;
84  else
85  return false;
86  }
87 }
88 
89 bool EvtSocketManager::remove(int fd)
90 {
91  FD_CLR(fd, &m_allset);
92  shutdown(fd, SHUT_RDWR);
93  close(fd);
94  vector<int>::iterator pos = find(m_fd.begin(), m_fd.end(), fd);
95  if (pos != m_fd.end()) {
96  m_fd.erase(pos);
97  return true;
98  } else
99  return false;
100 }
101 
102 
103 
104 
105 
Abstract base class for different kinds of events.