int main(void)
{
struct sockaddr_in servaddr, cliaddr;
socklen_t cliaddr_len;
int listenfd, connfd;
char buf[MAXLINE];
char str[INET_ADDRSTRLEN];
int i, n;
char header[MAX][MAXLENGTH];
char receive[512];
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
listen(listenfd, 20);
printf("Accepting connections ...\n");
while (1)
{
cliaddr_len = sizeof(cliaddr);
connfd = accept(listenfd,(struct sockaddr *)&cliaddr, &cliaddr_len);
if(connfd!=-1)
{
int pid = fork();
if (pid == 0)
{
while (1)
{
n=read(connfd, buf, MAXLINE);
if (n == 0)
{
printf("the other side has been closed.\n");
break;
}
buf[strlen(buf)+1]='\0';
strcat(receive,buf);
printf("received from %s at PORT %d\n",inet_ntop(AF_INET, &cliaddr.sin_addr, str, sizeof(str)),ntohs(cliaddr.sin_port));
}
}
else if(pid > 0) {
sleep(10);
printf("%s",receive);
parse(receive,strlen(receive),header);
}
}
else
{
continue; //继续监听或者break 执行下面 显示接收到的数据
}
}
printf("%s",receive);
if(resp(header)==1)
printf("OK");
close(connfd);
close(listenfd);//若不要一直监听的话,关闭监听描述符
exit(0);
}
结果:
Accepting connections ...
received from 127.0.0.1 at PORT 47412
received from 127.0.0.1 at PORT 47412
received from 127.0.0.1 at PORT 47412
received from 127.0.0.1 at PORT 47412
received from 127.0.0.1 at PORT 47412
received from 127.0.0.1 at PORT 47412
received from 127.0.0.1 at PORT 47412
received from 127.0.0.1 at PORT 47412
the other side has been closed.