多线程-阻塞IO模型

 

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<thread> 

#define MaxSize 2048
/*
tcp多线程并发,阻塞IO模式,
缺点:需要对套接字进行轮询读取,效率低。
缺点:当有很多客户端时, 需要开辟大量线程,浪费资源。
*/ void *Task(void *arg) { int sockfd = (long)arg; pthread_detach(pthread_self()); while (1) { char msg[MaxSize] = { '\0' }; int len = recv(sockfd, msg, MaxSize, 0); if (len > 0) { printf("recv %s \n", msg); //再发回去。 send(sockfd, msg, len, 0); } sleep(1); } return NULL; } int main() { unsigned short port = 8000; printf("TCP Server Started at port %d!\n", port); int sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd<0) { perror("socket"); exit(-1); } struct sockaddr_in my_addr; bzero(&my_addr, sizeof(my_addr)); my_addr.sin_family=AF_INET; my_addr.sin_port=htons(port); my_addr.sin_addr.s_addr=htonl(INADDR_ANY); printf("Binding server to port %d\n", port); int err_log=bind(sockfd, (struct sockaddr*)&my_addr, sizeof(my_addr)); if (err_log != 0) { perror("binding"); close(sockfd); exit(-1); } err_log=listen(sockfd,10); if (err_log!=0) { perror("listen"); close(sockfd); exit(-1); } printf("Waiting client...\n"); while (1) { size_t recv_len=0; struct sockaddr_in client_addr; char cli_ip[INET_ADDRSTRLEN] = ""; socklen_t cliaddr_len = sizeof(client_addr); int NewClient; NewClient = accept(sockfd, (struct sockaddr*)&client_addr, &cliaddr_len); if (NewClient < 0) { perror("accept"); continue; } inet_ntop(AF_INET, &client_addr.sin_addr, cli_ip, INET_ADDRSTRLEN); printf("client ip = %s\n", cli_ip); //每一个链接,创建一个线程,在线程中对客户端套接字进行读写。 pthread_t thread_id; pthread_create(&thread_id, NULL, &Task, (void *)NewClient); } close(sockfd); return 0; }

 

posted @ 2018-11-18 21:09  osbreak  阅读(165)  评论(0编辑  收藏  举报