使用循环堵塞等待客户端连接,连接到一个就开一条线程,当用以下代码,即每次ad重新初始化后其地址作为实参进行线程的创建,结果就是当有新客户端连接,开了新线程时,旧线程看起来会被停止,实际上是因为ad用了地址而不是值作为实参,所以当新连接进来时,ad的值被更改,但地址不变,旧线程所使用的ad内的值也随之变换,使得不同线程所使用的ad是一样的。
while(1) { socklen_t remotelen = sizeof(struct sockaddr); int ad = accept(sd,(sockaddr *)&remote_ip,&remotelen); if(ad == -1) { std::cout<<"accept remote ip fail"<<errno<<std::endl; return -1; } pthread_t tid; int ret = pthread_create(&tid,NULL,recvthread,(void *)&ad); if(ret == -1) { std::cout<<"create thread fail"<<std::endl; close(ad); } }
所以需要保留每个ad的值,比如用数组
int i=0; while(1) { socklen_t remotelen = sizeof(struct sockaddr); ad[i] = accept(sd,(sockaddr *)&remote_ip,&remotelen); if(ad[i] == -1) { std::cout<<"accept remote ip fail"<<errno<<std::endl; return -1; } pthread_t tid; int ret = pthread_create(&tid,NULL,recvthread,(void *)&ad[i]); if(ret == -1) { std::cout<<"create thread fail"<<std::endl; close(ad[i]); } i++; }
while(1) { socklen_t remotelen = sizeof(struct sockaddr); ad[i] = accept(sd,(sockaddr *)&remote_ip,&remotelen); if(ad[i] == -1) { std::cout<<"accept remote ip fail"<<errno<<std::endl; return -1; } pthread_t tid; int ret = pthread_create(&tid,NULL,recvthread,(void *)&ad[i]); if(ret == -1) { std::cout<<"create thread fail"<<std::endl; close(ad[i]); } i++; } 标签:std,sockaddr,ad,ip,TCP,线程,remotelen,一些,多线程 From: https://www.cnblogs.com/toriyung/p/18168781