C++播送通訊實例。本站提示廣大學習愛好者:(C++播送通訊實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C++播送通訊實例正文
本文實例講述了C++完成播送通訊的辦法。分享給年夜家供年夜家參考。詳細完成辦法以下:
播送通訊代碼框架:
1. 協定都是:
SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0);
2. 辦事端設置選項
BOOL bBroadcast = TRUE;
::setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char*)&bBroadcast, sizeof(BOOL));
3. 辦事端向255.255.255.255 這個播送地址發內容 客戶端收聽便可以了
辦事端代碼:
#include "InitSock.h"
#include <stdio.h>
VOID main()
{
CInitSock initSock;
SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0);
//設置播送就是設置這個選項
BOOL bBroadcast = TRUE;
::setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char*)&bBroadcast, sizeof(BOOL));
//設置播送地址
SOCKADDR_IN bcast;
bcast.sin_family = AF_INET;
bcast.sin_port = htons(4567);
bcast.sin_addr.S_un.S_addr = INADDR_BROADCAST; //::inet_addr("255.255.255.255");
printf("begin send the data:\r\n");
char sz[] = "this is the broadcast data";
while(TRUE)
{
::sendto(s, sz, sizeof(sz), 0, (sockaddr*)&bcast, sizeof(bcast));
::Sleep(5000);
}
}
客戶端代碼:
#include "InitSock.h"
#include <stdio.h>
void main()
{
CInitSock initSock;
SOCKET s = ::socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_port = ::htons(4567);
sin.sin_addr.S_un.S_addr = INADDR_ANY;
if (::bind(s, (sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR)
{
printf("bind error");
return;
}
printf("begin recv the broadcast data:\r\n");
char sz[256] = {0};
SOCKADDR_IN addrRemote;
int nLen = sizeof(SOCKADDR_IN); //這裡必需設置成這個年夜小
while (TRUE)
{
int nRet = ::recvfrom(s, sz, sizeof(sz), 0, (sockaddr*)&addrRemote, &nLen);
if (nRet > 0)
{
sz[nRet] = '\0';
printf(sz);
}
}
}
願望本文所述對年夜家的C++法式設計有所贊助。