上篇实现了TCP通信的例子。由于项目中需要一个服务器向多台客户端发送消息。
通过udp这种无连接的通信,将client.c增加一句
/* 设置通讯方式对广播,即本程序发送的一个消息,网络上所有主机均可以收到 */
yes = 1;
setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &yes, sizeof(yes));
来设置发送的消息为广播形式。
直接贴代码:
client.c
//
// client.c
// udp
//
// Created by lovekun on 14-11-2.
// Copyright (c) 2014年 care.jiangnan. All rights reserved.
//
/*client.c*/
#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> /* netbd.h is needed for struct hostent =) */
#define PORT 1234 /* Open Port on Remote Host */
#define MAXDATASIZE 100 /* Max number of bytes of data */
/*
udp广