otsdaq  v2_04_01
TCPSocket.h
1 #ifndef _ots_TCPSocket_h_
2 #define _ots_TCPSocket_h_
3 
4 #include <netinet/in.h>
5 #include <sys/types.h>
6 #include <mutex>
7 #include <string>
8 #include <vector>
9 
10 #include "artdaq/DAQdata/TCPConnect.hh"
11 #include "artdaq/DAQdata/TCP_listen_fd.hh"
12 
13 #define OTS_MAGIC 0x5F4F54534441515F /* _OTSDAQ_ */
14 
15 namespace ots
16 {
17 class TCPSocket
18 {
19  public:
20  TCPSocket(const std::string& senderHost,
21  unsigned int senderPort,
22  int receiveBufferSize = 0x10000);
23  TCPSocket(unsigned int listenPort, int sendBufferSize = 0x10000);
24  virtual ~TCPSocket(void);
25 
26  void connect(double tmo_s = 10.0);
27 
28  int send(const uint8_t* data, size_t size);
29  int send(const std::string& buffer);
30  int send(const std::vector<uint32_t>& buffer);
31  int send(const std::vector<uint16_t>& buffer);
32 
33  int receive(uint8_t* buffer,
34  unsigned int timeoutSeconds,
35  unsigned int timeoutUSeconds);
36  int receive(std::string& buffer,
37  unsigned int timeoutSeconds = 1,
38  unsigned int timeoutUSeconds = 0);
39  int receive(std::vector<uint32_t>& buffer,
40  unsigned int timeoutSeconds = 1,
41  unsigned int timeoutUSeconds = 0);
42 
43  protected:
44  TCPSocket(void);
45 
46  std::string host_;
47  unsigned int port_;
48 
49  int TCPSocketNumber_;
50  int SendSocket_;
51  bool isSender_;
52  int bufferSize_;
53  size_t chunkSize_;
54 
55  mutable std::mutex socketMutex_;
56 
57  private:
58  struct MagicPacket
59  {
60  uint64_t ots_magic;
61  unsigned int dest_port;
62  };
63  MagicPacket makeMagicPacket(unsigned int port)
64  {
65  MagicPacket m;
66  m.ots_magic = OTS_MAGIC;
67  m.dest_port = port;
68  return m;
69  }
70  bool checkMagicPacket(MagicPacket magic)
71  {
72  return magic.ots_magic == OTS_MAGIC && magic.dest_port == port_;
73  }
74 };
75 
76 } // namespace ots
77 
78 #endif