httpd.c

/* J. David's webserver */
/* This is a simple webserver.
* Created November 1999 by J. David Blackstone.
* CSE 4344 (Network concepts), Prof. Zeigler
* University of Texas at Arlington
*/
/* This program compiles for Sparc Solaris 2.6.
* To compile for Linux:
* 1) Comment out the #include <pthread.h> line.
* 2) Comment out the line that defines the variable newthread.
* 3) Comment out the two lines that run pthread_create().
* 4) Uncomment the line that runs accept_request().
* 5) Remove -lsocket from the Makefile.
*/
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <ctype.h>
#include <strings.h>
#include <string.h>
#include <sys/stat.h>
#include <pthread.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdint.h>

#define ISspace(x) isspace((int)(x))

#define SERVER_STRING "Server: jdbhttpd/0.1.0\r\n"
#define STDIN 0
#define STDOUT 1
#define STDERR 2

//处理从套接字上监听到的HTTP请求
void accept_request(void *);
//向客户端发送400报文
void bad_request(int);
//读取服务器上某个文件写入套接口
void cat(int, FILE *);
//向客户端发送500报文,表明执行cgi程序时出现错误
void cannot_execute(int);
//把错误信息写到perror并退出
void error_die(const char *);
//运行cgi程序处理请求
void execute_cgi(int, const char *, const char *, const char *);
//读取套接字的一行
int get_line(int, char *, int);
//把HTTP响应的头部写到套接字
void headers(int, const char *);
//向客户端发送404的响应报文,表明找不到请求的文件
void not_found(int);
//调用cat把服务器文件返回给客户端
void serve_file(int, const char *);
//初始化httpd服务,包括建立套接字、绑定端口、进行监听等
int startup(u_short *);
//向客户端发送501的响应报文,表明收到的HTTP请求所用的method不被支持
void unimplemented(int);

/**********************************************************************/
/* A request has caused a call to accept() on the server port to
* return. Process the request appropriately.
* Parameters: the socket connected to the client */
/**********************************************************************/
//处理从套接字上监听到的HTTP请求
//参数arg是accept函数返回的结果,是一个用于与连接成功的客户端进行通信的套接字描述符
void accept_request(void *arg)
{
//intptr_t是为了跨平台,其长度总是所在平台的位数
int client = (intptr_t)arg;
char buf[1024];
size_t numchars;
char method[255];
char url[255];
char path[512];
size_t i, j;
struct stat st;
int cgi = 0; /* becomes true if server decides this is a CGI
* program */
char *query_string = NULL;

//从套接口读取http请求的第一行,格式是:Method Request-URI HTTP-Version CRLF
numchars = get_line(client, buf, sizeof(buf));
i = 0; j = 0;
//解析Method,即第一个空格之前的内容,如果把method数组读满了,说明请求的Method是瞎写的
while (!ISspace(buf[i]) && (i < sizeof(method) - 1))
{
method[i] = buf[i];
i++;
}
j=i;
method[i] = '\0';

//只支持GET和POST方法
if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
{
unimplemented(client);
return;
}

//POST请求要调用cgi函数处理
if (strcasecmp(method, "POST") == 0)
cgi = 1;

i = 0;
//跳过多余的空格
while (ISspace(buf[j]) && (j < numchars))
j++;
//读取请求的url
while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < numchars))
{
url[i] = buf[j];
i++; j++;
}
url[i] = '\0';

if (strcasecmp(method, "GET") == 0)
{
query_string = url;
//解析参数之前的url
while ((*query_string != '?') && (*query_string != '\0'))
query_string++;
//带参数的GET请求也要调用cgi函数处理
if (*query_string == '?')
{
cgi = 1;
*query_string = '\0';
query_string++;
}
}

//所有的静态资源文件和cgi程序文件都默认放在htdocs目录下,url默认以'/'开头,所以"htdocs"后面就不用加了
//path字符串存储的就是htdocs+url的路径
sprintf(path, "htdocs%s", url);
//如果请求的url是目录而不是个文件,默认返回该目录下的index.html
if (path[strlen(path) - 1] == '/')
//strcat用于拼接两个字符串
strcat(path, "index.html");
//stat函数用于获取文件信息并保存在st里。获取成功返回0,失败返回-1
if (stat(path, &st) == -1) {
//把套接口的接受缓冲读完,相当于清空缓冲区
while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
numchars = get_line(client, buf, sizeof(buf));
//返回404报文
not_found(client);
}
else
{
//st_mode记录了文件的类型、设置、权限等信息,和S_IFMT进行按位与得到的是其中记录文件类型的bits,再和S_IFDIR比较判断是否是目录
//因为目录有可能不以'/'结尾,所以还要判断一次,是目录就默认返回其下的index.html
if ((st.st_mode & S_IFMT) == S_IFDIR)
strcat(path, "/index.html");
//判断文件是否有可执行权限,包括所有者、用户组、其他用户这三类人的权限
//对可执行文件的请求也要交给cgi函数处理
if ((st.st_mode & S_IXUSR) ||
(st.st_mode & S_IXGRP) ||
(st.st_mode & S_IXOTH) )
cgi = 1;
//如果不需要调用cgi函数,就直接给客户端返回文件
if (!cgi)
serve_file(client, path);
else
execute_cgi(client, path, method, query_string);
}
//处理完请求后关闭套接口
close(client);
}

/**********************************************************************/
/* Inform the client that a request it has made has a problem.
* Parameters: client socket */
/**********************************************************************/
//向客户端发送400报文
void bad_request(int client)
{
char buf[1024];

sprintf(buf, "HTTP/1.0 400 BAD REQUEST\r\n");
send(client, buf, sizeof(buf), 0);
sprintf(buf, "Content-type: text/html\r\n");
send(client, buf, sizeof(buf), 0);
sprintf(buf, "\r\n");
send(client, buf, sizeof(buf), 0);
sprintf(buf, "<P>Your browser sent a bad request, ");
send(client, buf, sizeof(buf), 0);
sprintf(buf, "such as a POST without a Content-Length.\r\n");
send(client, buf, sizeof(buf), 0);
}

/**********************************************************************/
/* Put the entire contents of a file out on a socket. This function
* is named after the UNIX "cat" command, because it might have been
* easier just to do something like pipe, fork, and exec("cat").
* Parameters: the client socket descriptor
* FILE pointer for the file to cat */
/**********************************************************************/
//读取服务器上某个文件写入套接口。其实就是以1024个字节为单位,把resource文件的内容send到套接口的发送缓冲
void cat(int client, FILE *resource)
{
char buf[1024];

fgets(buf, sizeof(buf), resource);
while (!feof(resource))
{
send(client, buf, strlen(buf), 0);
fgets(buf, sizeof(buf), resource);
}
}

/**********************************************************************/
/* Inform the client that a CGI script could not be executed.
* Parameter: the client socket descriptor. */
/**********************************************************************/
//向客户端发送500报文,表明执行cgi程序时出现错误
void cannot_execute(int client)
{
char buf[1024];

sprintf(buf, "HTTP/1.0 500 Internal Server Error\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, "Content-type: text/html\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, "\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, "<P>Error prohibited CGI execution.\r\n");
send(client, buf, strlen(buf), 0);
}

/**********************************************************************/
/* Print out an error message with perror() (for system errors; based
* on value of errno, which indicates system call errors) and exit the
* program indicating an error. */
/**********************************************************************/
//把错误信息写到perror并退出
void error_die(const char *sc)
{
//把错误信息输出到stderr
perror(sc);
//exit(0)表示正常退出,exit(1)表示异常退出
exit(1);
}

/**********************************************************************/
/* Execute a CGI script. Will need to set environment variables as
* appropriate.
* Parameters: client socket descriptor
* path to the CGI script */
/**********************************************************************/
//运行cgi程序处理请求
void execute_cgi(int client, const char *path,
const char *method, const char *query_string)
{
char buf[1024];
int cgi_output[2];
int cgi_input[2];
pid_t pid;
int status;
int i;
char c;
int numchars = 1;
int content_length = -1;

buf[0] = 'A'; buf[1] = '\0';
//如果是GET请求,只需要url,后面的内容都清空。所以其实没有实现处理带参数的GET请求
if (strcasecmp(method, "GET") == 0)
while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
numchars = get_line(client, buf, sizeof(buf));
else if (strcasecmp(method, "POST") == 0) /*POST*/
{
//对于POST请求,循环读取请求信息直到找到Content-Length字段,获取Content-Length字段的值
//因为请求报文中,报文头和数据段之间有一个换行符,所以读到换行时strcmp("\n", buf)==0,退出循环,此时已经读完了报文头,接着要读的就是POST携带的数据
numchars = get_line(client, buf, sizeof(buf));
while ((numchars > 0) && strcmp("\n", buf))
{
//结束符设在中间,后面的字符串就不会参与strcmp
buf[15] = '\0';
if (strcasecmp(buf, "Content-Length:") == 0)
content_length = atoi(&(buf[16]));
numchars = get_line(client, buf, sizeof(buf));
}
//Content-Length是-1可能是由于请求携带的数据太大了,因为atoi函数对数字大小有限制,数字过大可能就会返回-1
//此时返回400错误的报文
if (content_length == -1) {
bad_request(client);
return;
}
}
//既不是GET也不是POST,在accept_request函数中已经判断过了,所以不可能执行到这一行
else/*HEAD or other*/
{
}

//使用管道实现进程间通信
//pipe函数用于建立管道,成功返回0,失败返回-1。参数数组包含两个文件的描述符,通过cgi_output[0]读管道,通过cgi_output[1]写管道
//cgi_output通道用于子进程向主进程发送cgi程序执行的输出信息,cgi_input通道用于主进程向子进程发送POST请求的数据
if (pipe(cgi_output) < 0) {
//管道建立失败,返回500错误报文
cannot_execute(client);
return;
}
if (pipe(cgi_input) < 0) {
cannot_execute(client);
return;
}

//fork出一个子进程运行cgi程序,以下的代码就会有两个进程共同执行
//如果fork成功,子进程返回0,父进程返回子进程ID,如果失败则返回-1
if ( (pid = fork()) < 0 ) {
cannot_execute(client);
return;
}

//返回成功的状态码
sprintf(buf, "HTTP/1.0 200 OK\r\n");
send(client, buf, strlen(buf), 0);

//如果当前是子进程
if (pid == 0) /* child: CGI script */
{
char meth_env[255];
char query_env[255];
char length_env[255];

//dup2用于复制文件描述符
//把output管道的写口重定向到标准输出
dup2(cgi_output[1], STDOUT);
//把input管道的读口重定向到标准输入
dup2(cgi_input[0], STDIN);
//关闭output管道的读口和input管道的写口
close(cgi_output[0]);
close(cgi_input[1]);
sprintf(meth_env, "REQUEST_METHOD=%s", method);
//增加或修改环境变量,因为服务器与CGI程序交换信息的协作方式是通过环境变量实现的
putenv(meth_env);
if (strcasecmp(method, "GET") == 0) {
sprintf(query_env, "QUERY_STRING=%s", query_string);
putenv(query_env);
}
else { /* POST */
sprintf(length_env, "CONTENT_LENGTH=%d", content_length);
putenv(length_env);
}
//默认请求的文件是.cgi结尾的可执行文件,调用execl来执行该文件
execl(path, NULL);
//正常退出
exit(0);
//如果当前是父进程
} else { /* parent */
//关闭output管道的写口和input管道的读口
close(cgi_output[1]);
close(cgi_input[0]);
//如果是POST请求,此前已经读完了请求头,现在就是把POST的数据写入input管道,然后子进程中运行的cgi程序从该管道读取数据,执行相应操作
if (strcasecmp(method, "POST") == 0)
for (i = 0; i < content_length; i++) {
recv(client, &c, 1, 0);
write(cgi_input[1], &c, 1);
}
//从output通道中读取子进程运行的cgi程序的返回信息,并发送给客户端
while (read(cgi_output[0], &c, 1) > 0)
send(client, &c, 1, 0);

//关闭通道
close(cgi_output[0]);
close(cgi_input[1]);
//请求响应完成,清理子进程
waitpid(pid, &status, 0);
}
}

/**********************************************************************/
/* Get a line from a socket, whether the line ends in a newline,
* carriage return, or a CRLF combination. Terminates the string read
* with a null character. If no newline indicator is found before the
* end of the buffer, the string is terminated with a null. If any of
* the above three line terminators is read, the last character of the
* string will be a linefeed and the string will be terminated with a
* null character.
* Parameters: the socket descriptor
* the buffer to save the data in
* the size of the buffer
* Returns: the number of bytes stored (excluding null) */
/**********************************************************************/
//读取套接字的一行
//buf存储读取的数据,size是buf的长度,本文件里用到的buf都是1024bytes,返回值是buf的有效长度
int get_line(int sock, char *buf, int size)
{
int i = 0;
char c = '\0';
int n;

//buf满了或者读到换行符就停止
while ((i < size - 1) && (c != '\n'))
{
//recv函数从套接口中读取数据。套接口有发送缓冲和接受缓冲,send函数只是把数据写入发送缓冲,recv函数只是从接受缓冲中复制数据,而真正的数据传输是从发送缓冲传送到接受缓冲,这个传送过程是由协议完成的,这个接受缓冲其实就是TCP的滑动窗口
//第一个参数是套接字描述符
//第二个参数指明一个缓冲区,用来存放读取到的数据,因为每次只读一个字符,所以c就是一个char
//第三个参数是缓冲区的长度
//第四个参数用于设置收发数据的一些条件,一般设置为0
//返回的是从接受缓冲中复制的字节数
n = recv(sock, &c, 1, 0);
/* DEBUG printf("%02X\n", c); */
//如果读到了数据
if (n > 0)
{
//如果读到回车符'\r',下一个字符必须是换行符
//回车符和换行符不会存到buf里
if (c == '\r')
{
//MSG_PEEK表示只从缓冲区读取内容而不清除缓冲区,下次读取的还是相同的内容
//不清除缓冲区是为了防止不小心读到下一行,确定是换行符后再重新读取并清除缓冲区
n = recv(sock, &c, 1, MSG_PEEK);
/* DEBUG printf("%02X\n", c); */
if ((n > 0) && (c == '\n'))
recv(sock, &c, 1, 0);
else
c = '\n';
}
buf[i] = c;
i++;
}
//如果没读到换行符就已经读完了,则退出循环
else
c = '\n';
}
buf[i] = '\0';
//i是buf中实际存储的字节数
return(i);
}

/**********************************************************************/
/* Return the informational HTTP headers about a file. */
/* Parameters: the socket to print the headers on
* the name of the file */
/**********************************************************************/
//把HTTP响应的头部写到套接字
void headers(int client, const char *filename)
{
char buf[1024];
//filename没用上,可以根据文件类型设置Content-Type字段
(void)filename; /* could use filename to determine file type */

strcpy(buf, "HTTP/1.0 200 OK\r\n");
send(client, buf, strlen(buf), 0);
strcpy(buf, SERVER_STRING);
send(client, buf, strlen(buf), 0);
sprintf(buf, "Content-Type: text/html\r\n");
send(client, buf, strlen(buf), 0);
strcpy(buf, "\r\n");
send(client, buf, strlen(buf), 0);
}

/**********************************************************************/
/* Give a client a 404 not found status message. */
/**********************************************************************/
//向客户端发送404的响应报文,表明找不到请求的文件
void not_found(int client)
{
char buf[1024];

sprintf(buf, "HTTP/1.0 404 NOT FOUND\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, SERVER_STRING);
send(client, buf, strlen(buf), 0);
sprintf(buf, "Content-Type: text/html\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, "\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, "<HTML><TITLE>Not Found</TITLE>\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, "<BODY><P>The server could not fulfill\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, "your request because the resource specified\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, "is unavailable or nonexistent.\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, "</BODY></HTML>\r\n");
send(client, buf, strlen(buf), 0);
}

/**********************************************************************/
/* Send a regular file to the client. Use headers, and report
* errors to client if they occur.
* Parameters: a pointer to a file structure produced from the socket
* file descriptor
* the name of the file to serve */
/**********************************************************************/
//调用cat把服务器文件返回给客户端
void serve_file(int client, const char *filename)
{
FILE *resource = NULL;
int numchars = 1;
char buf[1024];

//先给buf随便写入一个'\0'结尾的字符串,因为下一行调用strcmp时,如果strcmp在buf中找不到结束符,可能会发生不可预料的错误,strcmp可能会一直向后比较,超出buf的空间范围,直到找到一个结束符为止
//随便往buf里写什么都无所谓,反正在get_line函数里都会被覆盖掉
buf[0] = 'A'; buf[1] = '\0';

//都已经知道请求的文件路径了,套接口接收缓冲里面剩下的东西就没用了,直接清空,大概是一些header相关的数据
while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
numchars = get_line(client, buf, sizeof(buf));

resource = fopen(filename, "r");
//难道stat函数会出错?为什么还要判断一次文件存不存在?
if (resource == NULL)
not_found(client);
else
{
//把报文头和文件内容发送到套接口的发送缓冲
headers(client, filename);
cat(client, resource);
}
fclose(resource);
}

/**********************************************************************/
/* This function starts the process of listening for web connections
* on a specified port. If the port is 0, then dynamically allocate a
* port and modify the original port variable to reflect the actual
* port.
* Parameters: pointer to variable containing the port to connect on
* Returns: the socket */
/**********************************************************************/
//初始化httpd服务,包括建立套接字、绑定端口、进行监听等
int startup(u_short *port)
{
//接受socket的返回值
int httpd = 0;
int on = 1;
//网络通信的地址
struct sockaddr_in name;

//创建套接字
//第一个参数是地址族,也就是IP地址类型,PF_INET表示IPv4地址。在windows中AF_INET与PF_INET完全一样,AF是Address Family的意思,PF是Protocol Family的意思,二者在linux或unix系统中可能有微小差别。
//第二个参数是通信类型,SOCK_STREAM表示流格式套接字,采用TCP协议进行传输。另一个选择是SOCK_DGRAM,表示数据报格式套接字,采用UDP协议传输。
//第三个参数是需要使用的协议,可以显式指定IPPROTO_TCP或IPPROTO_UDP,如果是0则根据前两个参数使用默认的协议。但是如果有多种协议支持给定的地址族和通信类型,系统就无法确定默认的协议。
//返回值是一个文件描述符,用于唯一标识一个socket。成功时返回非负整数值,失败时返回-1。文件描述符是一个非负整数,相当于系统给文件创造的索引值,比如0,1,2分别表示标准输入、标准输出、标准错误
httpd = socket(PF_INET, SOCK_STREAM, 0);
//如果创建失败就向系统报错
if (httpd == -1)
error_die("socket");
//地址的所有字段初始化为0
memset(&name, 0, sizeof(name));
//设置地址的协议族字段,在socket编程中只能是AF_INET
name.sin_family = AF_INET;
//设置地址的端口号。htons函数用于将整型变量从主机字节顺序转变成big-endian的网络字节顺序,网络字节顺序是TCP/IP中规定好的一种系统无关的数据表示格式
//htons用于转换2个字节的整数,而main函数中定义的port恰好是2个字节的u_short类型
name.sin_port = htons(*port);
//设置ip地址。htonl和htons功能相同,用于转换4个字节的整数。INADDR_ANY表示通配地址(0.0.0.0),也就是服务器上所有的网卡,不管是哪个网卡接收到的数据,只要端口匹配上就进行处理
name.sin_addr.s_addr = htonl(INADDR_ANY);
//setsockopt用于设置与套接字关联的选项
//第一个参数是配置选项的目标套接字描述符
//第二个参数是被设置的选项的级别,SOL_SOCKET表示通用套接字选项
//第三个参数是被设置的选项名,SO_REUSEADDR选项控制的是打开或关闭端口复用功能
//第四个参数是设置的选项值,on=1表示打开端口复用功能
//第五个参数是选项值的长度
//成功返回0。失败返回-1
//在调用bind之前一般都要打开SO_REUSEADDR选项,允许端口复用,也就是允许多个套接字绑定在同一个端口上
if ((setsockopt(httpd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))) < 0)
{
error_die("setsockopt failed");
}
//bind绑定套接字和本地地址,成功返回0。失败返回-1
if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0)
error_die("bind");
//端口号0是一种由系统指定动态生成的端口,如果把端口参数设为0,操作系统就会从动态端口号范围内搜索接下来可以使用的端口号
if (*port == 0) /* if dynamically allocating a port */
{
//socklen_t其实就是int的别名
socklen_t namelen = sizeof(name);
//getsockname返回与给定套接字关联的本地协议地址,获取的地址存储在name中。在以端口号0调用bind后,getsockname用于返回内核赋予的本地端口号。
//成功返回0。失败返回-1
if (getsockname(httpd, (struct sockaddr *)&name, &namelen) == -1)
error_die("getsockname");
//从系统分配的地址中解析出端口号赋给指针port
*port = ntohs(name.sin_port);
}
//以上的操作是在创建和配置套接字,也就是一个套接口的描述字,listen函数才是真正创建一个可接受连接的套接口,并监听申请的连接
//第二个参数5表示等待连接队列的最大长度
//创建成功返回0。失败返回-1
if (listen(httpd, 5) < 0)
error_die("listen");
//返回套接字
return(httpd);
}

/**********************************************************************/
/* Inform the client that the requested web method has not been
* implemented.
* Parameter: the client socket */
/**********************************************************************/
//向客户端发送501的响应报文,表明收到的HTTP请求所用的method不被支持
void unimplemented(int client)
{
char buf[1024];

sprintf(buf, "HTTP/1.0 501 Method Not Implemented\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, SERVER_STRING);
send(client, buf, strlen(buf), 0);
sprintf(buf, "Content-Type: text/html\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, "\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, "<HTML><HEAD><TITLE>Method Not Implemented\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, "</TITLE></HEAD>\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, "<BODY><P>HTTP request method not supported.\r\n");
send(client, buf, strlen(buf), 0);
sprintf(buf, "</BODY></HTML>\r\n");
send(client, buf, strlen(buf), 0);
}

/**********************************************************************/

int main(void)
{
int server_sock = -1;
u_short port = 4000;
int client_sock = -1;
struct sockaddr_in client_name;
socklen_t client_name_len = sizeof(client_name);
//linux下的pthread_t其实是unsigned long int的别名,代表线程的标识符
pthread_t newthread;

//初始化服务,获取套接字
server_sock = startup(&port);
printf("httpd running on port %d\n", port);
//死循环监听连接
while (1)
{
//accept函数从server_sock的等待连接队列中抽取第一个连接,创建一个与server_sock同类的新的套接口
//返回值是一个新的套接字描述符,这个socket包含的是客户端的ip和port信息,代表的是和客户端的新的连接
//client_name用于存储客户端的地址。client_name_len在调用函数时被设置为client_name结构体的长度,accept函数会根据client_name_len值的大小往client_name所指向的地址里写信息,当写入完成后,client_name_len会被重新设置为client_name中实际地址信息的长度
//成功时返回非负整数值,失败时返回-1
//所以server_sock仅仅用来监听新的连接,每次接收到新的连接都会创建新的socket来与客户端通信
client_sock = accept(server_sock,
(struct sockaddr *)&client_name,
&client_name_len);
if (client_sock == -1)
//客户端建立连接失败就退出整个程序,why?
error_die("accept");
/* accept_request(&client_sock); */
//pthread_create用于创建线程
//第一个参数是指向线程标识符的指针
//第二个参数用来设置线程属性,NULL表示使用默认属性
//第三个参数是线程所执行的函数的起始地址
//第四个参数默认为NULL,若上述函数需要参数,则在此设置函数参数的地址
//线程创建成功时返回0,创建失败则返回出错编号,反正不是0
if (pthread_create(&newthread , NULL, (void *)accept_request, (void *)(intptr_t)client_sock) != 0)
//线程创建失败只报错,不退出程序,相当于丢弃这个客户端连接
perror("pthread_create");
}

//close函数用于关闭文件,因为套接字的描述符本质上就是个文件描述符,所以close可以用来关闭套接口
//上面的死循环没有break,error_die直接退出程序,按理说应该不会执行到这一行呀???
close(server_sock);

return(0);
}

simpleclient.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
int sockfd;
int len;
struct sockaddr_in address;
int result;
char ch = 'A';

sockfd = socket(AF_INET, SOCK_STREAM, 0);
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = htons(9734);
len = sizeof(address);
result = connect(sockfd, (struct sockaddr *)&address, len);

if (result == -1)
{
perror("oops: client1");
exit(1);
}
write(sockfd, &ch, 1);
read(sockfd, &ch, 1);
printf("char from server = %c\n", ch);
close(sockfd);
exit(0);
}