代码:
#include <Windows.h> //需要包含该头文件
#include <stdio.h>
#pragma comment(lib,"Winmm.lib") //For timeSetEvent
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib") //加载 ws2_32.dll
unsigned short thisPort[8] = {1234,1235,1236,1237,1238,1239,1240,1241};
unsigned short otherPort[8] = {1242,1243,1244,1245,1246,1247,1248,1249};
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(thisPort[channel]);//端口号就作为通道信息来进行配置
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(otherPort[channel]);//端口号就作为通道信息来进行配置
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(thisPort[channel]);//端口号就作为通道信息来进行配置
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);
sndData(1, data, 128);
char buffer1[128];
revData(0, buffer1, 128);
for (int i = 0; i < 128; i++)
printf("buffer1:%d\n", buffer1[i]);
char buffer2[128];
revData(0, buffer2, 128);
for (int i = 0; i < 128; i++)
printf("buffer2:%d\n", buffer2[i]);
}
//定时器2的回调函数
void WINAPI TimerCallback2(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
{
//TODO 这边进行数据处理功能
}
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;
}
网络调试助手设置如下:
可以看出代码同时使用两路UDP和网络调试助手双工通信起来了。