1.网络编程是一个程序员必须掌握的一项技能,尤其c/c++程序员必须掌握,而实际应用中,绝大部分网络程序都不可能是单连接,那么就意味着需要处理并发问题,目前来说主流的linux下的网络模型基本都基于epoll,select,在大规模并发情况下性能较高,而多进程,多线程模型相对较少,多进程模型实际使用确实较少,进程间通讯和数据共享都不太方便,而多线程模型在小连接数,尤其在内部通讯还是有可取之处,可以利用多核优势,开发也简单,易于维护。
多线程模型分为几类,一个是来一个连接开一个线程,二是先开N个线程,每个同时监听要连接的客户端程序,也就是通常说的线程池,线程池可以减少创建和销毁线程的代价。
下面就是我自己写的一个多线程echo服务端程序,没有数据处理部分,仅仅是将收到的客户端数据返回给相应的客户端。
- #include<iostream>
- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
- #include<errno.h>
- #include<netdb.h>
- #include<sys/types.h>
- #include<sys/socket.h>
- #include<netinet/in.h>
- #include<arpa/inet.h>
- #include<netdb.h>
- #include<sys/time.h>
- #include<string.h>
- #include<pthread.h>
- using namespace std;
- int thread_count = 0;
- void *word_thread(void *p);
- int main(int argc, char*argv[])
- {
- int port = 0;
- if (argc != 3)
- {
- cout<<"command error"<<endl;
- exit(-1);
- }
- port = atoi(argv[1]);
- thread_count = atoi(argv[2]);
- int server_sock = 0;
- struct sockaddr_in server_addr;
- memset(&server_addr, 0, sizeof(server_addr));
- if((server_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
- {
- cout<<"create socket error"<<endl;
- exit(-1);
- }
- server_addr.sin_family = AF_INET;
- server_addr.sin_addr.s_addr =htonl(INADDR_ANY);
- server_addr.sin_port = htons(port);
- if(bind(server_sock, (struct sockaddr*)&server_addr,sizeof(sockaddr))
- == -1)
- {
- cout<<"bind error"<<endl;
- exit(-1);
- }
- if(listen(server_sock, 5) == -1)
- {
- cout<<"listent error"<<endl;
- exit(-1);
- }
- pthread_t *thread_id = new pthread_t[thread_count];
- for(int i = 0; i < thread_count; i++)
- {
- pthread_create(&thread_id[i], NULL, word_thread, &server_sock);
- }
- for(int j = 0; j < thread_count; j++)
- {
- pthread_join(thread_id[j], NULL);
- }
- return 0;
- }
- void *word_thread(void *p)
- {
- int *s = (int*)p;
- int listen_fd = *s;
- while(1)
- {
- struct sockaddr_in client_addr;
- memset(&client_addr, 0, sizeof(client_addr));
- unsigned int len = sizeof(client_addr);
- int new_sock= accept(listen_fd, (struct sockaddr*) &client_addr, &len);
- if(new_sock == -1)
- {
- cout<<"accept error"<<endl;
- }
- char recvbuf[1024] = {0};
- char sendbuf[1024] = {0};
- while(1)
- {
- if(recv(new_sock, recvbuf, sizeof(recvbuf), 0) <= 0)
- {
- cout<<"recv error"<<endl;
- close(new_sock);
- break;
- }
- sleep(1);
- strcpy(sendbuf, recvbuf);
- if(send(new_sock, sendbuf, sizeof(sendbuf), 0) <= 0)
- {
- cout<<"send error"<<endl;
- close(new_sock);
- break;
- }
- }
- }
- pthread_exit(NULL);
- return NULL;
- }