1 Star 0 Fork 0

20155339 / Linux

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
server3.c 1.64 KB
一键复制 编辑 原始数据 按行查看 历史
pingcuo 提交于 2017-11-12 15:36 . week8
/*
* echoservert.c - A concurrent echo server using threads
*/
/* $begin echoservertmain */
#include "csapp.h"
void echo(int connfd);
void *thread(void *vargp);
char *haddrp;
int main(int argc, char **argv)
{
int listenfd, *connfdp, port;
socklen_t clientlen=sizeof(struct sockaddr_in);
struct sockaddr_in clientaddr;
pthread_t tid;
if (argc != 2) {
fprintf(stderr, "usage: %s <port>\n", argv[0]);
exit(0);
}
port = atoi(argv[1]);
listenfd = Open_listenfd(port);
while (1) {
connfdp = Malloc(sizeof(int)); //line:conc:echoservert:beginmalloc
*connfdp = Accept(listenfd, (SA *) &clientaddr, &clientlen); //line:conc:echoservert:endmalloc
haddrp = inet_ntoa(clientaddr.sin_addr);
Pthread_create(&tid, NULL, thread, connfdp);
}
}
/* thread routine */
void *thread(void *vargp)
{
int connfd = *((int *)vargp);
Pthread_detach(pthread_self()); //line:conc:echoservert:detach
Free(vargp); //line:conc:echoservert:free
echo(connfd);
Close(connfd);
return NULL;
}
/* $end echoservertmain */
void echo(int connfd)
{
static char timestr[40];
time_t t;
struct tm *nowtime;
time(&t);
nowtime = localtime(&t);
strftime(timestr,sizeof(timestr),"%Y-%m-%d %H:%M:%S",nowtime);
size_t n;
char buf[MAXLINE];
rio_t rio;
Rio_readinitb(&rio, connfd);
while((n = Rio_readlineb(&rio, buf, MAXLINE)) != 0) { //line:netp:echo:eof
printf("server received %d bytes\n", (int)n);
printf("客户端IP:%s\n",haddrp);
printf("服务器实现者学号:20155339\n");
printf("当前时间:%s\n",timestr);
printf("\n");
Rio_writen(connfd, buf, n);
}
}
C
1
https://gitee.com/pingcuo/Linux.git
git@gitee.com:pingcuo/Linux.git
pingcuo
Linux
Linux
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891