实现网络时间服务功能,要求:(建议采用UDP协议)
- 客户端程序向服务器程序发送时间请求消息“What time is it now?”,在收到服务器发来的时间以“yyyy-mm-dd hh:mm:ss”的格式打印在屏幕上。
- 服务器程序能够并发(轮询)处理多个客户端的时间服务请求,并将服务器的系统时间发送给客户端,并在屏幕上打印出请求时间服务客户端的IP地址。
环境:Vmare15+ Ubuntu18+codeblocks
/*服务端程序*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <arpa/inet.h>
#define BUFFLEN 1024
#define SERVER_PORT 8888
#define BACKLOG 5
#define PIDNUMB 5
static void handle_connect(int s)
{
struct sockaddr_in from;/*客户端地址*/
socklen_t len = sizeof(from);
int n = 0;
char buff[BUFFLEN];
time_t now;/*时间*/
/*主处理过程*/
while(1)
{
memset(buff, 0, BUFFLEN);/*清零*/
/*接收客户端连接*/
n = recvfrom(s, buff, BUFFLEN,0,(struct sockaddr*)&from, &len);
/*打印请求客户端的IP和端口号*/
printf("RECV IP: %s PORT:%d\r\n",inet_ntoa(from.sin_addr),htons(from.sin_port));
/*接收发送方数据*/
if(n > 0 && !strncmp(buff, "What time is it now?", 20))/*判断是否合法接收数据*/
{
memset(buff, 0, BUFFLEN);/*清零*/
now = time(NULL);/*当前时间*/
//sprintf(buff, "%24s\r\n",ctime(&now));/*将时间复制入缓冲区*/
strftime(buff, sizeof(buff), "%Y-%m-%d %H:%M:%S\r\n", localtime(&now));
sendto(s, buff, strlen(buff),0, (struct sockaddr*)&from, len);/*发送数据*/
}
}
}
void sig_int(int num)/*SIGINT信号处理函数*/
{
exit(1);
}
int main(int argc, char *argv[])
{
int s_s;/*服务器套接字文件描述符*/
struct sockaddr_in local;/*本地地址*/
signal(SIGINT, sig_int);
/*建立UDP套接字*/
s_s = socket(AF_INET, SOCK_DGRAM, 0);
/*初始化地址*/
memset(&local, 0, sizeof(local));/*清零*/
local.sin_family = AF_INET;/*AF_INET协议族*/
local.sin_addr.s_addr = htonl(INADDR_ANY);/*任意本地地址*/
local.sin_port = htons(SERVER_PORT);/*服务器端口*/
/*将套接字文件描述符绑定到本地地址和端口*/
bind(s_s, (struct sockaddr*)&local, sizeof(local));
/*处理客户端连接*/
pid_t pid[PIDNUMB];
int i =0;
for(i=0;i<PIDNUMB;i++)
{
pid[i] = fork();
if(pid[i] == 0)/*子进程*/
{
handle_connect(s_s);
}
}
while(1);
return 0;
}
/*客户端*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#define BUFFLEN 1024
#define SERVER_PORT 8888
int main(int argc, char *argv[])
{
int s;/*服务器套接字文件描述符*/
struct sockaddr_in server;/*本地地址*/
char buff[BUFFLEN];/*收发数据缓冲区*/
int n = 0;/*接收字符串长度*/
socklen_t len = 0;/*地址长度*/
s = socket(AF_INET, SOCK_DGRAM, 0);/*建立UDP套接字*/
/*初始化地址初始化*/
memset(&server, 0, sizeof(server));/*清零*/
server.sin_family = AF_INET;/*AF_INET协议族*/
server.sin_addr.s_addr = htonl(INADDR_ANY);/*任意本地地址*/
server.sin_port = htons(SERVER_PORT);/*服务器端口*/
while(1){
memset(buff, 0, BUFFLEN);/*清零*/
strcpy(buff, "What time is it now?");/*复制发送字符串*/
/*发送数据*/
sendto(s, buff, strlen(buff), 0, (struct sockaddr*)&server,
sizeof(server));
memset(buff, 0, BUFFLEN);/*清零*/
/*接收数据*/
len = sizeof(server);
n = recvfrom(s, buff, BUFFLEN, 0, (struct sockaddr*)&server, &len);
/*打印消息*/
if(n >0){
printf("%s",buff);
}
sleep(1);
}
close(s);
return 0;
}
运行结果: