VC++ 用Socket怎样编持续接收数据的程序
发布网友
发布时间:2022-04-20 10:14
我来回答
共2个回答
热心网友
时间:2023-07-01 07:10
你这种是用的阻塞模式,就是 Accept和Receive 都会卡住不动,直到有新连接或者有新数据。
实际使用场景中,阻塞模式,一个线程专门Accept 有新的连接之后,为每一个连接再创建一个线程来处理 Receive,也就是对于服务器来说,假设当前有10个工作的连接,那么至少需要11个线程。
你只需要开几个专门的线程来负责接受连接和接收数据就可以了。
这种阻塞模式不适合大并发量的网络程序,测试小程序没问题,大并发量时需要使用非阻塞模式,比如一般常用的select模式
百度 “select模型” 就可以搜到。追问可以有具体实例发给我吗?
热心网友
时间:2023-07-01 07:10
VC++ 用Socket持续接收数据的程序举例如下:
while(1) { //client receiving code
if ((numbytes = recv(sockfd, buf, MAXDATASIZE, 0)) == -1)
perror("recv");
}
buf[numbytes] = '\0';
printf("numbytes is %d\n", numbytes);
printf("client: received '%s'\n", buf);
}
以下是输出:
numbytes is 0
client: received '12345'
numbytes is 0
client: received '6'
numbytes is 0
client: received ''
numbytes is 0
client: received ''
numbytes is 0
client: received ''
numbytes is 0
client: received ''
numbytes is 0
client: received ''
numbytes is 0
client: received ''
numbytes is 0
client: received ''
numbytes is 0
client: received ''