VC++ 用Socket怎样编持续接收数据的程序

2025-05-13 12:56:37
推荐回答(2个)
回答1:

你这种是用的阻塞模式,就是 Accept和Receive 都会卡住不动,直到有新连接或者有新数据。

实际使用场景中,阻塞模式,一个线程专门Accept 有新的连接之后,为每一个连接再创建一个线程来处理 Receive,也就是对于服务器来说,假设当前有10个工作的连接,那么至少需要11个线程。
你只需要开几个专门的线程来负责接受连接和接收数据就可以了。
这种阻塞模式不适合大并发量的网络程序,测试小程序没问题,大并发量时需要使用非阻塞模式,比如一般常用的select模式
百度 “select模型” 就可以搜到。

回答2:

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 ''