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