本文主要介绍如何在vxworks中实现BroadCast,具有一定的参考价值。有兴趣的朋友可以参考一下。希望大家看完这篇文章后收获多多。让边肖带你去了解一下。
有了单播和组播,广播就不能运行了。broadcast、BroadCast和单播的区别在于地址。广播的地址是255 . 255 . 255 . 255 . 255;而且广播数据不会被路由器转发,局限于局域网,否则因为网络风暴,广播码其实更简单。直接写一个请参考单播/组播的例子。
服务器在单播的基础上略有变化。
调用Socket()打开一个套接字。
调用bind()来指定端口信息。
调用setsockopt()加入广播
调用recvfrom()以阻止接收
最后,调用close()关闭套接字。
广播客户端更简单。
调用Socket()打开一个套接字。
指定广播地址和端口信息
通过调用sendto()发送数据
最后,调用close()关闭套接字。
完整的代码如下
# include stdio . h/* pritnf()*/# include stdlib . h/* malloc()*/# include socklib . h/* socket()*/# include inetlib . h/* 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 local addr;struct sockaddr _ in peerAddrint addrSize=sizeof(struct sockaddr);int opt=1;int fdint numchar *缓冲区;if(PORT=2000)PORT=HOST _ PORT;if(SIZE=0)SIZE=MIN _ SIZE;if(TIMES=0)TIMES=MIN _ TIMES;printf(',大小,端口);/* Open 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 <stdio.h> /* pritnf() */
#include <stdLib.h> /* malloc() */
#include <sockLib.h> /* socket() */
#include <inetLib.h> /* 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<size; num++) buffer[num] = (num%26)+'a';
/* 服务器地址信息 */
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”这篇文章对大家有帮助,同时也希望大家多多支持,关注行业资讯频道,更多相关知识等着你来学习!
内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/155156.html