C++ 接收UDP数据并按时间命名写入TXT
#include <iostream>
#include <WinSock2.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include<fstream>
using namespace std;
#pragma comment(lib,"WS2_32.lib")
//udp通信接收端
void createUdpRecv()
{
//初始化Socket
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
sockaddr_in recvAddr;
sockaddr_in sendAddr;
SOCKET recvSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
recvAddr.sin_family = AF_INET;
//绑定ip
recvAddr.sin_addr.s_addr = inet_addr("192.168.8.89");
//绑定端口
recvAddr.sin_port = htons(8001);
int ret = bind(recvSock, (sockaddr*)&recvAddr, sizeof(recvAddr));
printf("192.168.8.89 bind %s\n", ret >= 0 ? "success." : "fail.");
while (true)
{
//接收区长度根据需要设置
char recvBuf[1024] = "";
int sendAddrLen = sizeof(sendAddr);
int ret = recvfrom(recvSock, recvBuf, 1024, 0, (sockaddr*)&sendAddr, &sendAddrLen);
if (ret >= 0)
{
//printf("receiving data == %s\n", recvBuf);
for(int i=0;i<=88;i++){ //循环方法 去除\00等特定字符
//TODO
if(recvBuf[i]=='\000' or recvBuf[i]=='\001')
recvBuf[i]='\056';
}
cout<<recvBuf<<endl;
Sleep(1000); //运行太快,暂停,等待txt完成写入
time_t t = time(0);
char tmp[64];
char tmps[100];
strftime( tmp, sizeof(tmp), "%Y%m%d%H%M%S",localtime(&t) );
sprintf(tmps,"D:\\fsdata\\%s.txt",tmp);
ofstream OutFile(tmps);
OutFile <<recvBuf;
OutFile.close();
}
}
}
void HideWindow() { //隐藏窗口
HWND hwnd = GetForegroundWindow(); //获取程序启动时的窗口
if (hwnd) {
ShowWindow(hwnd, SW_HIDE); //设置指定窗口的显示状态
}
}
int main()
{
//防止程序可以重复开启运行
// 创建互斥量
HANDLE m_hMutex = CreateMutex(NULL, FALSE, "1");
// 如果程序已经存在并且正在运行
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
CloseHandle(m_hMutex);
m_hMutex=NULL;
return FALSE;
}
HideWindow();
createUdpRecv();
return 0;
}
注明:DevC++下要在编译选项中加入 -lwsock32,否则报错。
部分数组的取值或者循环赋值为我在编写仪器接口时内容需要,使用时应当按实际情况修改!!!