请教各位大虾。我写了个C/S结构的程序(用winsocket),我的客户连接数量总是不能超过4000;一只维持在3960多,无论什么配置的机器都一样,服务端和客户端分开在两台机器运行也是这样。不知道什么原因?
我的QQ55722176,EMAIL:cwx133@163.com;请高手指点一下,也希望认识更多的编程爱好者,谢谢了!
我的代码如下:
服务端:
int main(int argc, char* argv[])
{
WSADATA wsaData;
SOCKADDR_IN InternetAddr;//地址结构
SOCKET Listen;//服务器socket
SOCKET Accept;//接受客户socket
if (WSAStartup((WORD)(0x0202), (LPWSADATA)(&wsaData) ) != 0)
{
return 0;
}
//打开一个服务器socket
if ((Listen = WSASocket(AF_INET, SOCK_STREAM/*UDP(数据报)应为SOCK_DGRAM*/, 0, NULL, 0,WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET)
{
return 0;
}
InternetAddr.sin_family = AF_INET;
InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);
InternetAddr.sin_port = htons(PORT);
if(bind(Listen, (PSOCKADDR) &InternetAddr, sizeof(InternetAddr)) == SOCKET_ERROR)
{
return 0;
}
if(listen(Listen,5000) == SOCKET_ERROR)
{
return 0;
}
//SOCKADDR_IN ClientAddr; // 定义一个客户端得地址结构作为参数
//int addr_length=sizeof(ClientAddr);
while(TRUE)
{
if((Accept = WSAAccept(Listen, NULL, NULL, NULL, 55555)) == SOCKET_ERROR)//方式2.2
{
return 0;
}
}
//***************************************************************
客户端:
//初始化
CLIENT::CLIENT()
{
WSADATA wData;
OutTime=0;
if(0!=WSAStartup( MAKEWORD(2,2), &wData ))
return ;
client = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0,WSA_FLAG_OVERLAPPED);
if(INVALID_SOCKET==client||client==NULL)
return;
}
bool CLIENT::Connect(unsigned long timeout){
sockaddr_in target;
target.sin_family = AF_INET;
target.sin_port = htons(PORT); //服务器端口
char strip[]="192.168.1.168";
target.sin_addr.s_addr = inet_addr(strip); //服务器IP
printf(" 目标IP地址为: %s\n 目标端口为: %d (TCP/IP %d)\n\n",inet_ntoa(target.sin_addr),PORT,target.sin_port);
int sp=0;
long clock1=clock();
while(clock()-clock1<timeout){
sp=connect(client, (struct sockaddr*)&target, sizeof(target));//试图连接
if(0==sp){//连接成功
return true;
}
Sleep(1);
}
return false;
}
//关闭连接
void CLIENT::Close()
{
if(0!=closesocket(client))
return;
//-------------------------------------------------
}int main(int argc, char* argv[])
{
for(i=0;i<5000;++i){
CLIENT c;
if(c.Connect()){
//c.Send(1,str,strlen(str));
//printf("第 %5d 个连接成功 发送数据量为 %d\n",i,strlen(str));
//Sleep(1);
}
}
}