设计说明
在Linux平台下,创建一个基于UDP的简易时间服务器,包含服务器端和客户端。同时支持多个客户端同时连接,采用信号驱动的方式实现。
信号驱动编程,简单来说就是创建一个信号处理函数,如sig_io_handler(),当有消息到来时,程序执行信号处理函数,执行完后再返回。
客户机可以发送一下四种命令
- Gettime:获取时间,发送服务器当前时间给客户机。
- Getdate:获取日期,发送服务器当前日期给客户机。
- Getdatetime:获去服务器日期时间信息。
- shutdown:关闭服务器。
服务器流程图
代码
Server.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>
//用于获取时间
time_t timep;
//套接字的文件id
int sockfd;
//发送缓冲区和接受缓冲区
char send_buf[30];
char recv_buf[30];
//接收到的字符串数目
int recv_num;
//IP地址,127.0.0.1为本机
#define DSET_IP_ADDRESS "127.0.0.1"
//存放客户机的地址
struct sockaddr_in addr_client;
//用于recvfrom()函数
int serv_len;
//直接获取到的时间是从1900开始的秒数,这个函数转换为现在的日期
int GetDate(char *DateTime)
{
struct tm *nowTime;
time(&timep);
nowTime = localtime(&timep);
sprintf(DateTime, "%04d-%02d-%02d",
nowTime->tm_year + 1900, nowTime->tm_mon + 1, nowTime->tm_mday);
return 0;
}
//直接获取到的时间是从1900开始的秒数,这个函数转换为现在的时间
int GetTime(char *DateTime)
{
struct tm *nowTime;
time(&timep);
nowTime = localtime(&timep);
/* 系统时间,格式: HHMMSS */
sprintf(DateTime, "%02d:%02d:%02d",
nowTime->tm_hour, nowTime->tm_min, nowTime->tm_sec);
return 0