- 论坛徽章:
- 0
|
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#define SERVPORT 4444 /*服务器监听端口号 */
#define BACKLOG 10 /* 最大同时连接请求数 */
void GetSystemTime();
int buf[256];
char recvbuf[256];
char timebuf[64];
main(void)
{
int recvbytes;
int sockfd,client_fd; /*sock_fd:监听socket;client_fd:数据传输socket */
struct sockaddr_in local_addr; /* 本机地址信息 */
struct sockaddr_in remote_addr; /* 客户端地址信息 */
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket创建出错!" ;
exit(1);
}
local_addr.sin_family=AF_INET;
local_addr.sin_port=htons(SERVPORT);
local_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(local_addr.sin_zero), ;
if (bind(sockfd, (struct sockaddr *)&local_addr, sizeof(struct sockaddr))== -1)
{
perror("bind出错!" ;
exit(1);
}
if (listen(sockfd, BACKLOG) == -1)
{
perror("listen出错!" ;
exit(1);
}
while(1)
{
int sin_size = sizeof(struct sockaddr_in);
if ((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr, &sin_size)) == -1)
{
perror("accept出错" ;
continue;
}
printf("来自: %s 的连接n", inet_ntoa(remote_addr.sin_addr));
if (!fork()) /* 子进程代码段 */
{
while(1)
{
GetSystemTime();
if (send(client_fd, timebuf,256,0) == -1)
{
perror("send出错!" ;
close(client_fd);
exit(0);
}
sleep(5);
/*
if(recv(client_fd,recvbuf,256,0)<=0)
{
printf("%s已断开n",inet_ntoa(remote_addr.sin_addr));
close(client_fd);
exit(0);
}
*/
}
close(client_fd);
}
recv(client_fd, recvbuf, 256, 0);
// printf("%sn", recvbuf);
}
close(sockfd);
}
void GetSystemTime()
{
time_t timep;
struct tm *p;
time(&timep);
p=localtime(&timep);
sprintf(timebuf,"%4d%2d%2d%2d%2d%2d",
(p->tm_year+1900),(p->tm_mon+1),p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec);
}
这是我写的,关于系统对时的问题 |
|