C++广播通信实例
时间:2020-10-08 13:27:48|栏目: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));
::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 <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);
}
}
}
#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++程序设计有所帮助。
上一篇:centos 7 vscode cmake 编译c++工程的教程详解
栏 目:C代码
下一篇:浅谈使用Rapidxml 库遇到的问题和分析过程(分享)
本文标题:C++广播通信实例
本文地址:http://www.codeinn.net/misctech/8519.html