server.c:
#include
#include
#include //perror错误输出
#include
#include
#include
#include
#include
#include
#include
#define PORT 8999
#define MAXSIZE (8 * 4096)
int main(int argc, char *argv[])
{
int sockfd, peer, len;
struct sockaddr_in serv_addr, clnt_addr;
char recvmsg[MAXSIZE], sendmsg[MAXSIZE];
sockfd = socket(AF_INET, SOCK_STREAM, 0);//创建socket
if (sockfd < 0) {
perror("socket error");
return -1;
}
/* 配置socket */
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(serv_addr.sin_zero), 8);
/* 绑定socket */
if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) < 0) {
perror("bind err");
return -1;
}
/* 主动socket转为被动监听socket */
if (listen(sockfd, 1) < 0) {
perror("listen error");
return -1;
}
/* 循环监听 */
len = sizeof(clnt_addr);
while (1) {
printf("begin to accept\n");
peer = accept(sockfd, (struct sockaddr *)&clnt_addr, &len);/* 接收连接 */
if (peer < 0) {
perror("Server: accept failed.\n");
continue;
}
memset(recvmsg, 0, MAXSIZE);
memset(sendmsg, 0, MAXSIZE);
if (read(peer, recvmsg, sizeof(recvmsg)) < 0) {
perror("recv err");
break;
}
printf("client: %s\n", recvmsg);
if (!strcmp(recvmsg, "quit")) {
printf("close a connection\n");
break;
}
strcpy(sendmsg, "I get your req");
write(peer, sendmsg, strlen(sendmsg) + 1);
close(peer);
}
return 0;
}
阅读(9944) | 评论(1) | 转发(1) |