代码:
#include //需要包含该头文件
#include
#pragma comment(lib,"Winmm.lib") //For timeSetEvent
#include
#pragma comment(lib, "ws2_32.lib") //加载 ws2_32.dll
unsigned short port[8] = {1234,1235,1236,1237,1238,1239,1240,1241};
void sndData(int channel, char* data, int len)
{
printf("我是第一个周期函数,周期为1s\n");
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
//创建套接字
SOCKET sock = socket(PF_INET, SOCK_DGRAM, 0);
//本机地址信息
struct sockaddr_in thisAddr;
memset(&thisAddr, 0, sizeof(thisAddr)); //每个字节都用0填充
thisAddr.sin_family = PF_INET;
thisAddr.sin_addr.s_addr = inet_addr("172.24.64.1");//这个ip要改换成自动获取本机ip
thisAddr.sin_port = htons(2345);//端口号就作为通道信息来进行配置
bind(sock, (SOCKADDR*)&thisAddr, sizeof(SOCKADDR));
struct sockaddr_in servAddr;
memset(&servAddr, 0, sizeof(servAddr)); //每个字节都用0填充
servAddr.sin_family = PF_INET;
servAddr.sin_addr.s_addr = inet_addr("172.24.64.1");//这个ip要改换成自动获取本机ip
servAddr.sin_port = htons(1234);//端口号就作为通道信息来进行配置
sendto(sock, data, len, 0, (struct sockaddr*)&servAddr, sizeof(servAddr));
closesocket(sock);
}
void revData(int channel, char* buffer, int len)
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
//创建套接字
SOCKET sock = socket(PF_INET, SOCK_DGRAM, 0);
//服务器地址信息
struct sockaddr_in thisAddr;
memset(&thisAddr, 0, sizeof(thisAddr)); //每个字节都用0填充
thisAddr.sin_family = PF_INET;
thisAddr.sin_addr.s_addr = inet_addr("172.24.64.1");//这个ip要改换成自动获取本机ip
thisAddr.sin_port = htons(2345);//端口号就作为通道信息来进行配置
bind(sock, (SOCKADDR*)&thisAddr, sizeof(SOCKADDR));
struct sockaddr_in servAddr;
int addrLen = sizeof(servAddr);
int dataLen = recvfrom(sock, buffer, len, 0, (struct sockaddr*)&servAddr, &addrLen);
printf("dataLen%d\n", dataLen);
closesocket(sock);
}
//定时器1的回调函数
void WINAPI TimerCallback1(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
{
char data[128];
for (int i = 0; i < 128; i++)
data[i] = i;
sndData(0, data, 128);
char buffer[128];
revData(0, buffer, 128);
for (int i = 0; i < 128; i++)
printf("buffer:%d\n", buffer[i]);
}
//定时器2的回调函数
void WINAPI TimerCallback2(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
//创建套接字
SOCKET sock = socket(PF_INET, SOCK_DGRAM, 0);
//服务器地址信息
struct sockaddr_in servAddr;
memset(&servAddr, 0, sizeof(servAddr)); //每个字节都用0填充
servAddr.sin_family = PF_INET;
servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servAddr.sin_port = htons(2345);
printf("我是第二个周期函数,周期为2s\n");
char buffer[100] = "xky";
sendto(sock, buffer, strlen(buffer), 0, (struct sockaddr*)&servAddr, sizeof(servAddr));
}
int main()
{
DWORD_PTR dwUser = NULL;
// 设置定时器
int timerID1 = timeSetEvent(1000, 1, (LPTIMECALLBACK)TimerCallback1, dwUser, TIME_PERIODIC);
if(timerID1 != NULL)
printf("定时器1创建成功\n");
int timerID2 = timeSetEvent(2000, 1, (LPTIMECALLBACK)TimerCallback2, dwUser, TIME_PERIODIC);
if(timerID2 != NULL)
printf("定时器2创建成功\n");
while(1)
{
;
}
timeKillEvent(timerID1); //关闭定时器1
timeKillEvent(timerID2); //关闭定时器2
return 0;
}
网络调试助手设置:
运行代码: