重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这篇文章主要介绍了vxworks中如何实现BroadCast,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
临邑网站建设公司创新互联,临邑网站设计制作,有大型网站制作公司丰富经验。已为临邑上1000家提供企业网站建设服务。企业网站搭建\成都外贸网站建设要多少钱,请找那个售后服务好的临邑做网站的公司定做!
广播的代码其实更简单,直接参考单播/组播的例子写一个
Server是在单播的基础上略加改动
调用socket()打开一个Socket
调用bind()指定Port信息
调用setsockopt()加入广播
调用recvfrom()阻塞接收
最后,调用close()关闭Socket
广播Client更简单了
调用socket()打开一个Socket
指定广播地址和Port信息
调用sendto()发送数据
最后,调用close()关闭Socket
完整代码如下
#include
/* pritnf() */ #include
/* malloc() */ #include
/* socket() */ #include
/* struct sockaddr_in */
#define HOST_PORT 60000
#define MIN_SIZE 10
#define MIN_TIMES 10
void broadServer (int port, int size, int times)
{
struct sockaddr_in localAddr;
struct sockaddr_in peerAddr;
int addrSize = sizeof(struct sockaddr);
int opt = 1;
int fd;
int num;
char *buffer;
if(port <= 2000) port = HOST_PORT;
if(size <= 0) size = MIN_SIZE;
if(times <= 0) times = MIN_TIMES;
printf (">, size, port);
/* 打开Socket */
fd = socket (AF_INET, SOCK_DGRAM, 0);
/* 指定本地地址信息 */
localAddr.sin_family = AF_INET;
localAddr.sin_port = htons (port);
localAddr.sin_addr.s_addr = INADDR_ANY;
bind (fd, (struct sockaddr *)&localAddr, sizeof(struct sockaddr));
/* 加入广播 */
setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(int));
buffer = (char *)malloc (size);
while ((times--)>0)
{
/* 接收广播数据 */
num = recvfrom (fd, buffer, size, 0,
(struct sockaddr *)&peerAddr, &addrSize);
if (num < 0) break;
printf (" broadServer: recv %d chars from %s\n",
num, inet_ntoa(peerAddr.sin_addr));
}
/* 关闭Socket */
close (fd);
free (buffer);
printf (" broadServer: end\n");
}
#include
/* pritnf() */ #include
/* malloc() */ #include
/* socket() */ #include
/* struct sockaddr_in */
#define HOST_PORT 60000
#define MIN_SIZE 1
#define MIN_TIMES 1
void broadClient (int port, int size, int times)
{
struct sockaddr_in serverAddr;
int opt = 1;
int fd;
char *buffer;
int num;
if(port <= 2000) port = HOST_PORT;
if(size <= 0) size = MIN_SIZE;
if(times<= 0) times= MIN_TIMES;
buffer = (char *)malloc(size);
for(num=0; num
/* 服务器地址信息 */
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons (port);
serverAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
printf (" broadClient: try to send %d chars %d times to %s:%d\n",
size, times, inet_ntoa(serverAddr.sin_addr), port);
/* 打开Socket */
fd = socket (AF_INET, SOCK_DGRAM, 0);
while ((times--)>0)
{
/* 发送数据到BroadCast Server */
num = sendto(fd, buffer, size, 0,
(struct sockaddr *)&serverAddr, sizeof(struct sockaddr));
printf (" broadClient: send %d chars\n", num);
}
/* 关闭Socket */
close (fd);
free (buffer);
printf (" broadClient: send finished\n");
}
运行情况如下如下
感谢你能够认真阅读完这篇文章,希望小编分享的“vxworks中如何实现BroadCast”这篇文章对大家有帮助,同时也希望大家多多支持创新互联,关注创新互联行业资讯频道,更多相关知识等着你来学习!