群播技術
群播:
是指在發送者和每一個接收者之間實現點對多點網路連接
實例操作
實現一個基於C/S模式的群播通信,伺服器程式負責建立群播組,並提供一個鍵盤輸入介面,輸入的資訊向組內成員群播發送;客戶端加入群播組,接收伺服器的資訊並顯示,若發現資訊中包含quit則退出程式
1.伺服器程式
是指在發送者和每一個接收者之間實現點對多點網路連接
實例操作
實現一個基於C/S模式的群播通信,伺服器程式負責建立群播組,並提供一個鍵盤輸入介面,輸入的資訊向組內成員群播發送;客戶端加入群播組,接收伺服器的資訊並顯示,若發現資訊中包含quit則退出程式
1.伺服器程式
#include "stdio.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "netdb.h"
#include "unistd.h"
#include "stdlib.h"
int main(void)
{
int server_socket;
struct sockaddr_in address;
server_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (server_socket < 0)
{
perror("socket");
return 0;
}
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("224.0.0.1");
address.sin_port = htons(5555);
while(1)
{
char buf[200];
printf("input your word:>");
scanf("%s",buf);
if(sendto(server_socket, buf,sizeof(buf), 0,(struct sockaddr *)&address, sizeof(address)) < 0)
{
perror("sendto");
return ;
}
}
}
2.客戶端程式
#include "stdio.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "netdb.h"
#include "unistd.h"
#include "stdlib.h"
int main(void)
{
struct ip_mreq multiaddress;
int serveraddress_len;
int client_socket;
struct sockaddr_in serveraddress;
/*bzero(&serveraddress, sizeof(serveraddress));*/
memset(&serveraddress, 0, sizeof(serveraddress));
serveraddress.sin_family = AF_INET;
serveraddress.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddress.sin_port = htons(5555);
if((client_socket = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket");
return 0;
}
int opt = 1;
if(setsockopt(client_socket, SOL_SOCKET, SO_REUSEADDR,&opt, sizeof(opt)) < 0)
{
perror("setsockopt:SO_REUSEADDR");
return 0;
}
if(bind(client_socket, (struct sockaddr *)&serveraddress, sizeof(serveraddress)) < 0)
{
perror("bind");
return 0;
}
// 婓肮珨跺翋儂奻輛俴嫘畦扢离杶諉諳
multiaddress.imr_multiaddr.s_addr = inet_addr("224.0.0.1");
multiaddress.imr_interface.s_addr = htonl(INADDR_ANY);
// 樓嫘畦郪
if (setsockopt(client_socket,IPPROTO_IP,IP_ADD_MEMBERSHIP,&multiaddress, sizeof(multiaddress)) < 0)
{
perror("IP_ADD_MEMBERSHIP");
return 0;
}
while(1)
{
char buf[200];
serveraddress_len = sizeof(serveraddress);
if(recvfrom(client_socket, buf, 200, 0, (struct sockaddr *)&serveraddress, &serveraddress_len) < 0)
{
perror("recvfrom");
}
printf("msg from server: %s\n", buf);
if(strcmp(buf,"quit") == 0)
{
if(setsockopt(client_socket, IPPROTO_IP, IP_DROP_MEMBERSHIP,&multiaddress, sizeof(multiaddress)) < 0)
{
perror("setsockopt:IP_DROP_MEMBERSHIP");
}
close(client_socket);
return 0;
}
}
}
留言
張貼留言