您好,登錄后才能下訂單哦!
這篇文章主要介紹了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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。