????????本文给出C++例程,实现windows系统与北醒CE30-D面阵雷达UDP通信。北醒CE30-D面阵雷达默认IP地址为192.168.1.80,端口号为2368。本使用程序从电脑向雷达发出获取版本指令,随后雷达向电脑发送版本信息。具体程序及运行结果如下
#include <iostream>
#include <Winsock2.h>
#include <WS2tcpip.h>
#pragma comment (lib, "ws2_32")
class UDP_SR {
private:
SOCKET sock_Local;
SOCKADDR_IN serv_Local_Addr, serv_Remote_Addr;
public:
int err = 0; //0: no error 1:winsock load error 2:failed to create socket 3:failed to connect
int state = 0;
UDP_SR()
{
//========================================================================================
//load socket
//========================================================================================
WORD w = MAKEWORD(2, 2);
WSADATA wsa;
if (WSAStartup(w, &wsa) != 0)
{
err = 1;
std::cout << "1:winsock load error\n";
return;
}
//========================================================================================
//create socket
//========================================================================================
serv_Remote_Addr.sin_family = AF_INET;
serv_Remote_Addr.sin_port = htons(2368);
serv_Remote_Addr.sin_addr.S_un.S_un_b.s_b1 = 192;
serv_Remote_Addr.sin_addr.S_un.S_un_b.s_b2 = 168;
serv_Remote_Addr.sin_addr.S_un.S_un_b.s_b3 = 1;
serv_Remote_Addr.sin_addr.S_un.S_un_b.s_b4 = 80;
sock_Local = socket(AF_INET, SOCK_DGRAM, 0);
if (sock_Local == SOCKET_ERROR)
{
err = 2;
std::cout << "2:failed to create socket\n";
return;
}
}
//========================================================================================
//receive
//========================================================================================
int Recv(char* data)
{
int size = sizeof(sockaddr);
int end = recvfrom(sock_Local, data, strlen(data), 0, (sockaddr *)(&serv_Remote_Addr), &size);
data[end] = '\0';
return end;
}
//========================================================================================
//send
//========================================================================================
void Send(char* data)
{
int i = sendto(sock_Local, data, strlen(data), 0, (sockaddr*)(&serv_Remote_Addr), sizeof(sockaddr));
}
};
int main()
{
char recvData[1024];
UDP_SR udp_sr = UDP_SR();
char version[51] = "version ";
//获取version
udp_sr.Send(version);
printf("version: \n");
bool recvMark = udp_sr.Recv(recvData);
if (recvMark)
{
printf(recvData);
}
else
{ }
printf("\n");
}
????????运行结果如下,版本为d9.8.9。
|