多线程实现服务器
//线程需要调用的函数
void pthread_work(struct argc *argc2) { int flag; struct argc argc1; argc1.sock_clt = argc2->sock_clt; argc1.sock_serv = argc2->sock_serv; printf("%d,%d\n",argc1.sock_clt,argc1.sock_serv); char buffer[1024]; strcpy(buffer, "this is server! welcome!\n"); //send(sock_client, buffer, 1024, 0); send(argc1.sock_clt, buffer, 1024, 0); bzero(buffer,sizeof(buffer)); //flag = recv(sock_client, buffer, 1024, 0); flag = recv(argc1.sock_clt, buffer, 1024, 0); if(flag < 0){ perror("recv error!\n"); close(argc1.sock_serv); return; } printf("recv : %s\n",buffer); while(1){ bzero(buffer,sizeof(buffer)); //flag = recv(sock_client, buffer, 1024, 0); recv(argc1.sock_clt, buffer, 1024, 0); if(flag < 0){ perror("recv error!\n"); close(argc1.sock_serv); return; } printf("i have recv buffer\n"); printf("recv : %s\n",buffer); if(strcmp(buffer,"quit") == 0){ printf("quit!!!\n"); break; } } close(argc1.sock_serv); pthread_exit(0); }
//在这个函数中需要把accept后的执行过程开启一个线程来执行
void server::startListen() { int flag = listen(sock_serv, 5); if(flag < 0){ perror("listen error!\n"); close(sock_serv); return; } //char buffer[1024]; while(1){ //bzero(buffer,sizeof(buffer)); struct sockaddr_in client_addr; int size = sizeof(client_addr); int sock_client = accept(sock_serv, (struct sockaddr*)(&client_addr), (unsigned int*)(&size)); if(sock_client < 0){ perror("accept error!\n"); continue; } printf("%d\n",sock_client); argc arg1; arg1.sock_serv = sock_serv; arg1.sock_clt = sock_client; pthread_t new_thread; flag = pthread_create(&new_thread,NULL,(void*(*)(void*))(&pthread_work),(void*)(&arg1)); if(flag != 0){ perror("thread creation failed!\n"); continue; } } }
在这里用eclipse配置C++开发,但是当使用多线程函数时,会由于Linux没有提供而无法找到线程函数,所以我们不仅要添加头文件,而且要在编译时候配置工程的属性,找到你所使用C++ Builder中的Setting的G++ Linker添加library,其中library添加pthread,path中添加cryto。这时就可以了。你也可以参考这里:好地方
这次的源码要保留一下了~~~下载地址:这里