linux下用C++写UDP通信程序该怎么写

如题所述

用ACE,它提供了很完善的一套构架。

#include "ace/SOCK_Dgram_Mcast.h"
#include "ace/INET_Addr.h"
#include "ace/OS.h"
#include "ace/ACE.h"
#include "ace/Log_Msg.h"

int ACE_TMAIN (int argc, char* argv[])
{
ACE_Time_Value ti = ACE_Time_Value (0, 20000);
ACE_INET_Addr local_addr ((u_short) 9000);
ACE_INET_Addr recv_addr ;

ACE_SOCK_Dgram recv_dgram;
//打开端口
if (recv_dgram.open (local_addr) == -1) {
ACE_DEBUG ((LM_ERROR, "%p\n", "Recieving data gram open"));
ACE_OS::exit (-1);
}

ACE_Time_Value t = ACE_Time_Value::zero;
while (1) {
//recieve data gram
char buf[2048];
//接收UDP数据,
ssize_t recv = recv_dgram.recv (buf, 2048, recv_addr);
//显示接收了多少数据,以及数据的来源
ACE_DEBUG ((LM_DEBUG, "%M [%t %N:%l] %s:%d recieved %d\n", recv_addr.get_host_addr (), recv_addr.get_port_number (), recv));
if (recv <= 0) {
ACE_DEBUG ((LM_DEBUG, "%M [%t %N:%l] Can't recieve any data gram from the port (%s:%d)\n", recv_addr.get_host_addr (),recv_addr.get_port_number ()));
ACE_OS::sleep (ti);
continue;
}
}
return 0;
}
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答