这篇文章主要介绍了vxworks中如何实现BroadCast,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
广播的代码其实更简单,直接参考单播/组播的例子写一个
Server是在单播的基础上略加改动
调用socket()打开一个Socket
调用bind()指定Port信息
调用setsockopt()加入广播
调用recvfrom()阻塞接收
最后,调用close()关闭Socket
广播Client更简单了
调用socket()打开一个Socket
指定广播地址和Port信息
调用sendto()发送数据
最后,调用close()关闭Socket
完整代码如下
#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 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 <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”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。