多线程服务器在不等待客户端连接的情况下退出
Multithread server exits without waiting for the connect from client
Linux套接字编程问题。
我正在开发一个多线程服务器,它可以接受来自多个客户端的连接。我的问题是,当我运行以下代码时,它会创建10个线程,然后在不等待客户端连接的情况下退出。有人能告诉我我的代码出了什么问题吗?非常感谢。
// include the library for socket programming
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
// include other useful library
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
#include <pthread.h>
#include <fstream>
#include <time.h>
using namespace std;
static int ListenSoc;
#define LISTENPORT 6000
#define THREADNUM 10
void *AcceptAndService(void *){
int ClientSoc;
socklen_t CliLen;
struct sockaddr_in CliAdd;
CliLen=sizeof(CliAdd);
memset((char *)&CliAdd,0,sizeof(CliAdd));
//accept the connect from the client to do the login
if(ClientSoc=accept(ListenSoc,(struct sockaddr*)&CliAdd,&CliLen)){
cout<<"connection from "<<inet_ntoa(CliAdd.sin_addr)<<" has foundn";
}
pthread_exit(NULL);
}
int main(){
//create the thread
pthread_t thread[THREADNUM];
//Doing the listen
struct sockaddr_in SerAdd;
ListenSoc=socket(AF_INET,SOCK_STREAM,0);
// set the address
memset((char *)&SerAdd,0,sizeof(SerAdd));
SerAdd.sin_port=htons(LISTENPORT);
SerAdd.sin_family=AF_INET;
SerAdd.sin_addr.s_addr = INADDR_ANY;
//bind
if(bind(ListenSoc,(struct sockaddr*)&SerAdd,sizeof(SerAdd))==-1)
cout<<"Error in bind";
else
cout<<"Bind success";
//listen
if(listen(ListenSoc,5)==-1)
cout<<"Error in listen";
else
cout<<"nt the register server is waiting for the connection...n"<<endl;
//Accept the connect from client
int i;
for(i=0;i<THREADNUM;i++){
cout<<"Accept thread "<<i<<" is being created"<<endl;
pthread_create(&thread[i], NULL, AcceptAndService, NULL);
}
return 0;
}
您必须在for循环之后调用pthread_join,以等待线程结束:
int i;
for(i=0;i<THREADNUM;i++){
cout<<"Accept thread "<<i<<" is being created"<<endl;
pthread_create(&thread[i], NULL, AcceptAndService, NULL);
}
for(i=0;i<THREADNUM;i++){
pthread_join(thread[i], NULL);
}
相关文章:
- QTcpSocket在不阻塞GUI的情况下重新连接到服务器
- 在不知道套接字的情况下关闭网络连接
- 在没有管理员权限的情况下连接到同一网络中的命名管道
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- 如何在没有侦听器的情况下创建 TCP 连接?
- 在不关闭连接的情况下接收整个页面
- 如何在不使用对象的情况下连接字符串、整数和浮点数
- 如何在不将其连接到终端的情况下运行'screen',以便我可以在C++ (qt) 应用程序中捕获输出?
- 在单元测试中测试连接丢失(在节俭的C++应用程序中或一般情况下)
- 我可以在不重新连接的情况下多次使用BIO_puts、BIO_read吗
- std::string和const char情况下的连接优先级
- C++ 我可以在没有计时器的情况下制作 boost::asio 连接插座吗?
- 提升异步 TCP 客户端在没有物理连接的情况下写入时不返回错误
- 在没有 MySql 连接器的情况下建立 MySQL 连接以进行C++
- 多线程服务器在不等待客户端连接的情况下退出
- 是否可以在没有接收器实例的情况下将信号连接到静态插槽
- 在没有连接的情况下调用C++Boost异步服务器处理程序
- 在不关闭连接的情况下,在循环中增强asio加密
- 在不轮询GetMessage()的情况下检测USB连接/断开连接
- Boost::asio::acceptor语言 - 在旧连接仍然打开的情况下接受新连接