本文发表在 rolia.net 枫下论坛for(;;) {
new_sock = accept(sockfd,(struct sockaddr *)&remote, &addrlen);
if (new_sock < 0) {
perror("Error on accept");
exit(1);
}
printf("\nConnection from host %s, port %d, socket %d\n",
inet_ntoa(remote.sin_addr), ntohs(remote.sin_port),new_sock);
//start to process incoming data
bzero(buf, BUFSIZ);
/*process the data*/
bytesread = read(new_sock, buf, sizeof(buf) - 1);
if (bytesread <= 0) {
if (close(new_sock))
perror("close");
continue;
}
//construct request structure from client
struct acp_server request;
request.command = buf;
request.arg1 = buf + strlen(request.command) + 1;
request.arg2 = buf + strlen(request.command) + 1 + strlen(request.arg1) + 1;
printf("command = %s\n", request.command);
printf("arg1 = %s\n", request.arg1);
printf("arg2 = %s\n", request.arg2);
//process client request
process_client_request(request, new_sock);
//close socket when finsih client request
if (close(new_sock))
perror("close");
}
在process_client_request 这个函数里处理, 打开文件, 读取文件的数据并通过SOCKET送到客户端, 数据发送完后, 使用fclose 关闭文件句柄,
process_client_request 函数退出后, 关闭SOCKET,接着又开始下一次的循环。更多精彩文章及讨论,请光临枫下论坛 rolia.net
new_sock = accept(sockfd,(struct sockaddr *)&remote, &addrlen);
if (new_sock < 0) {
perror("Error on accept");
exit(1);
}
printf("\nConnection from host %s, port %d, socket %d\n",
inet_ntoa(remote.sin_addr), ntohs(remote.sin_port),new_sock);
//start to process incoming data
bzero(buf, BUFSIZ);
/*process the data*/
bytesread = read(new_sock, buf, sizeof(buf) - 1);
if (bytesread <= 0) {
if (close(new_sock))
perror("close");
continue;
}
//construct request structure from client
struct acp_server request;
request.command = buf;
request.arg1 = buf + strlen(request.command) + 1;
request.arg2 = buf + strlen(request.command) + 1 + strlen(request.arg1) + 1;
printf("command = %s\n", request.command);
printf("arg1 = %s\n", request.arg1);
printf("arg2 = %s\n", request.arg2);
//process client request
process_client_request(request, new_sock);
//close socket when finsih client request
if (close(new_sock))
perror("close");
}
在process_client_request 这个函数里处理, 打开文件, 读取文件的数据并通过SOCKET送到客户端, 数据发送完后, 使用fclose 关闭文件句柄,
process_client_request 函数退出后, 关闭SOCKET,接着又开始下一次的循环。更多精彩文章及讨论,请光临枫下论坛 rolia.net