UDP面向无连接,数据发送端不管接收端有没有接收到或是否启动都将数据发送,所以接收端接收的数据有待验证,这也暗示着接收端和发送端启动顺序不限。
以下小实例仓促完成仅供学习讨论和参考:
发送端:
#include<stdlib.h>
#include<iostream>
#include<stdio.h>
#include<conio.h>
#include<winsock2.h>
#include<windows.h>
#include "atltime.h"
using namespace std;
#pragma comment(lib,"ws2_32.lib")
void main()
{
SOCKET sock;
sockaddr_in addrto;
WSADATA wsdata;
bool bsocket;
//启动SOCKET库,版本为2.0
WSAStartup(0x0202,&wsdata);
sock = WSASocket(AF_INET,SOCK_DGRAM,0,NULL,0,WSA_FLAG_OVERLAPPED);
bsocket = true;
addrto.sin_family = AF_INET;
addrto.sin_addr.s_addr = INADDR_BROADCAST;
addrto.sin_port = htons(8000);
bool opt = true;
//设置该套接字为广播类型,
setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(char FAR *)&opt,sizeof(opt));
int nlen =sizeof(addrto);
CTime t;
ZeroMemory(&t,sizeof(t));
while(1)
{
Sleep(1000);
t = CTime::GetCurrentTime();
CString strtime = t.Format(_T("%H:%M:%S SendDataTest"));
int ret = sendto(sock,strtime.GetBuffer(0),strtime.GetLength() + 1,0,(sockaddr*)&addrto,nlen);
if(ret == SOCKET_ERROR)
{
printf("%d/n",WSAGetLastError());
}
else
{
printf("%s\n",strtime.GetBuffer(0));
}
}
return;
}
接收端:
#include<stdlib.h>
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<winsock2.h>
#include<windows.h>
#pragma comment(lib,"ws2_32.lib")
void main(void)
{
SOCKET sock;
sockaddr_in a;
WSADATA wsdata;
bool optval; //启动SOCKET库,版本为2.0
WSAStartup(0x0202,&wsdata);
optval=true; //然后赋值给两个地址,一个用来绑定套接字,一个用来从网络上的广播地址接收消息;
a.sin_family = AF_INET;
a.sin_addr.s_addr = INADDR_ANY;
a.sin_port = htons(8000);
int fromlength = sizeof(SOCKADDR);
sock = socket(AF_INET,SOCK_DGRAM,0);
setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(char FAR *)&optval,sizeof(optval));
bind(sock,(sockaddr *)&a,sizeof(sockaddr_in));
char buf[256];
ZeroMemory(buf,256);
while(1)
{
recvfrom(sock,buf,256,0,(struct sockaddr FAR *)&a,(int FAR *)&fromlength);
printf("Receive *:%s \n",buf);
ZeroMemory(buf,256);
Sleep(1000);
}
return ;
}