#include
using namespace std;
#pragma comment(lib,"Ws2_32.lib")
int StartupSocket()
{
WSADATA data;
int rc = WSAStartup(MAKEWORd(2,2), &data);
if(NO_ERROR != rc)
{
cout<<"startup socket failed!"<
}
return rc;
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
//create udp socket
int UdpSocket(SOCKET &udp)
{
udp = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if(INVALID_SOCKET == udp)
{
cout<<"create socket failed!"<
}
return udp;
}
WSAEVENT hUdpEvent = NULL;
int UdpCreateEvent(void)
{
if(NULL == hUdpEvent)
{
hUdpEvent = WSACreateEvent();
if(NULL == hUdpEvent)
{
cout<<"Net event create failed!"<
}
}
return (int)hUdpEvent;
}
int UdpRegEvent(SOCKET &udp)
{
return WSAEventSelect(udp,hUdpEvent,FD_WRITE | FD_READ);
}
sockaddr_in hssAddr;
int UdpBind(SOCKET &udp,int port=20104,unsigned long addr = 0)
{
hssAddr.sin_family = AF_INET;
hssAddr.sin_port = htons(port);
hssAddr.sin_addr.s_addr = htonl(addr);
int ret = bind(udp,(SOCKADDR *)&hssAddr,sizeof(hssAddr));
if(0 != ret)
{
cout<<"bind socket error!"<
return ret;
}
typedef int (* UdpHssMsgHandle)(SOCKET &udp,int msgType);
int UdpEventOccur(SOCKET &udp,HANDLE hEvent,UdpHssMsgHandle msg)
{
WSANETWORKEVENTS networkEvents;
int ret = 0;
while(true)
{
WSAWaitForMultipleEvents(1,&hEvent,FALSE,INFINITE,FALSE);
//可信
ret = WSAEnumNetworkEvents(udp,hEvent,&networkEvents);
if(0 != ret)
{
cout<<"error occurs when wait for events"<
}
if((networkEvents.lNetworkEvents & FD_READ) && (networkEvents.iErrorCode[FD_READ_BIT] == 0))
{
//recvfrom
msg(udp,1);
}
if(networkEvents.lNetworkEvents & FD_WRITE)
{
//sendto
msg(udp,2);
}
}
return 0;
}
int UDP_Test(SOCKET &udp,int msgType)
{
char buf[255];
int fromlen = 0;
int ret = 0;
memset(buf,0,255);
sockaddr_in msgAddr;
msgAddr.sin_family = AF_INET;
msgAddr.sin_port = hssAddr.sin_port;
msgAddr.sin_addr.s_addr = hssAddr.sin_addr.s_addr;
ret = recvfrom(udp,buf,255,0,(sockaddr *)&msgAddr,&fromlen);
buf[fromlen] = '\0';
cout<<"receive data:"<
return 0;
}
//清场函数
int UdpClean(void)
{
WSACleanup();
if(NULL != hUdpEvent)
{
WSACloseEvent(hUdpEvent);
}
return 0;
}
int main()
{
SOCKET server;
StartupSocket();
UdpCreateEvent();
UdpSocket(server);
UdpBind(server);
UdpRegEvent(server);
UdpEventOccur(server,hUdpEvent,&UDP_Test);
closesocket(server);
UdpClean();
return 1;
}
问题已解决:recvfrom(udp,buf,255,0,(sockaddr *)&msgAddr,&fromlen);
fromlen需传入msgAddr的大小才行