C++广播通信实例
本文实例讲述了C++实现广播通信的方法。分享给大家供大家参考。具体实现方法如下:
广播通信代码框架:
1. 协议都是:
SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0);
2. 服务端设置选项
BOOL bBroadcast = TRUE;
::setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char*)&bBroadcast, sizeof(BOOL));
3. 服务端向255.255.255.255 这个广播地址发内容 客户端收听就可以了
服务端代码:
#include "InitSock.h"
#include <stdio.h>
VOID main()
{
CInitSock initSock;
SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0);
//设置广播就是设置这个选项
BOOL bBroadcast = TRUE;
::setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char*)&bBroadcast, sizeof(BOOL));
//设置广播地址
SOCKADDR_IN bcast;
bcast.sin_family = AF_INET;
bcast.sin_port = htons(4567);
bcast.sin_addr.S_un.S_addr = INADDR_BROADCAST; //::inet_addr("255.255.255.255");
printf("begin send the data:\r\n");
char sz[] = "this is the broadcast data";
while(TRUE)
{
::sendto(s, sz, sizeof(sz), 0, (sockaddr*)&bcast, sizeof(bcast));
::Sleep(5000);
}
}
客户端代码:
#include "InitSock.h"
#include <stdio.h>
void main()
{
CInitSock initSock;
SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_port = ::htons(4567);
sin.sin_addr.S_un.S_addr = INADDR_ANY;
if (::bind(s, (sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR)
{
printf("bind error");
return;
}
printf("begin recv the broadcast data:\r\n");
char sz[256] = {0};
SOCKADDR_IN addrRemote;
int nLen = sizeof(SOCKADDR_IN); //这里必须设置成这个大小
while (TRUE)
{
int nRet = ::recvfrom(s, sz, sizeof(sz), 0, (sockaddr*)&addrRemote, &nLen);
if (nRet > 0)
{
sz[nRet] = '\0';
printf(sz);
}
}
}
希望本文所述对大家的C++程序设计有所帮助。