recv.cpp
Go to the documentation of this file.
1 
23 #include "udp_bc_broker/recv.h"
24 
25 using namespace std;
26 
27 namespace udp_bc_broker{
28 
29  UdpRecver::UdpRecver(int port)
30  {
31  setvbuf(stdout, NULL, _IONBF, 0);
32  fflush(stdout);
33 
34  //bind address
35  bzero(&addrto, sizeof(struct sockaddr_in));
36  addrto.sin_family = AF_INET;
37  addrto.sin_addr.s_addr = htonl(INADDR_ANY);
38  addrto.sin_port = htons(port);
39 
40  //broadcast address
41  bzero(&from, sizeof(struct sockaddr_in));
42  from.sin_family = AF_INET;
43  from.sin_addr.s_addr = htonl(INADDR_ANY);
44  from.sin_port = htons(port);
45 
46  if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
47  cout<<"socket error!"<<endl;
48  exit(-1);
49  }
50 
51  const int opt = 1;
52  int nb = 0;
53  nb = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));
54  if(nb == -1) {
55  cout<<"set socket error!"<<endl;
56  exit(-1);
57  }
58 
59  if(bind(sock,(struct sockaddr *)&(addrto), sizeof(struct sockaddr_in)) == -1) {
60  cout<<"bind error!"<<endl;
61  exit(-1);
62  }
63 
64  len = sizeof(sockaddr_in);
65  buf = new char[10000];
66  }
67 
68  UdpRecver::~UdpRecver()
69  {
70  process_thread_->interrupt();
71  process_thread_->join();
72  delete process_thread_;
73 
74  delete[] buf;
75  }
76 
77  void UdpRecver::process_msg()
78  {
79  while(true) {
80  int ret = recvfrom(sock, buf, 10000, 0, (struct sockaddr*)&from, (socklen_t*)&len);
81  if(ret <= 0) {
82  cout<<"read error...."<<sock<<endl;
83  }
84  else {
85  std::vector<uint8_t> msg_data;
86  for(int i = 0; i < ret; i++) {
87  msg_data.push_back(buf[i]);
88  }
89  callback(msg_data);
90  }
91  sleep(0.1);
92  }
93  }
94 
95  void UdpRecver::receive(boost::function<void(const vector<uint8_t>&)> callBack)
96  {
97  callback = callBack;
98  process_thread_ = new boost::thread(&UdpRecver::process_msg, this);
99  }
100 };
void callback(const vector< uint8_t > &msg)
Definition: test_recv.cpp:27


udp_bc_broker
Author(s):
autogenerated on Mon Jun 10 2019 14:02:40