這篇文章主要介紹了vxworks中如何實現(xiàn)BroadCast,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
臨邑網(wǎng)站建設公司創(chuàng)新互聯(lián),臨邑網(wǎng)站設計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為臨邑上1000家提供企業(yè)網(wǎng)站建設服務。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設要多少錢,請找那個售后服務好的臨邑做網(wǎng)站的公司定做!
廣播的代碼其實更簡單,直接參考單播/組播的例子寫一個
Server是在單播的基礎上略加改動
調(diào)用socket()打開一個Socket
調(diào)用bind()指定Port信息
調(diào)用setsockopt()加入廣播
調(diào)用recvfrom()阻塞接收
最后,調(diào)用close()關(guān)閉Socket
廣播Client更簡單了
調(diào)用socket()打開一個Socket
指定廣播地址和Port信息
調(diào)用sendto()發(fā)送數(shù)據(jù)
最后,調(diào)用close()關(guān)閉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)
{
/* 接收廣播數(shù)據(jù) */
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));
}
/* 關(guān)閉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)
{
/* 發(fā)送數(shù)據(jù)到BroadCast Server */
num = sendto(fd, buffer, size, 0,
(struct sockaddr *)&serverAddr, sizeof(struct sockaddr));
printf (" broadClient: send %d chars\n", num);
}
/* 關(guān)閉Socket */
close (fd);
free (buffer);
printf (" broadClient: send finished\n");
}
運行情況如下如下
感謝你能夠認真閱讀完這篇文章,希望小編分享的“vxworks中如何實現(xiàn)BroadCast”這篇文章對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識等著你來學習!