我正在写一个关于多线程的TCP连接测试,出现了一个我无法解决的奇怪现象。
该程序非常简单。我们有一个服务器要接受,三个客户端要连接。最后,服务器会调用send()
将状态返回给客户端并执行类似的循环。但不幸的是,当服务器接受大约30000个连接时,它停止返回客户端,客户端将超时退出。
我尝试增加系统端口范围,减少时间等待秒数,并减慢 TCP 连接速度,但它不起作用并正确关闭了套接字。
还有其他原因吗?客户端代码:
while ( true )
/*connect server */
{
initSocketLocal(&client_addr,0);//
client_socket = socket(AF_INET,SOCK_STREAM,0);
if( client_socket < 0)
{
printf("Create Socket Failed!\n");
return -1;
}
if( bind(client_socket,(struct sockaddr*)&client_addr,sizeof(client_addr)))
{
printf("Client Bind Port Failed!\n");
close(client_socket);
return -1;
}
initSocket(&server_addr,DATANODE_PORT_READ,ip);
if((connect(client_socket,(struct sockaddr*)&server_addr, server_addr_length)) < 0)
{
perror ("can not connect to server:"); //find error
printf("client count is %d...\n", clientCount);
return -1;
}
usleep ( 100000 ) ;
clientCount++;
printf("client count is %d...\n", clientCount);
int length = recv ( client_socket ,res ,sizeof ( res ), 0);
if (length > 0)
{
printf ("recv buf is %s \n", res );
}
close(client_socket);
return 0;
}
并将代码作为流:
while( true )
/*wait for connect*/
{
socklen_t length = sizeof (struct sockaddr );
printf("listening ..... \n");
pthread_mutex_lock(&m_read);//lock clifd
if ((clifd = accept(sockRead,( struct sockaddr * ) & cliaddr, & length)) < 0 )
{
perror ("can not accept socket:");
break;
}
printf("Read Accept fd %d\n",clifd);
pthread_create (&t,NULL,handler,&clifd);
}
void* handler(void*arg)
{
int fd = *((int *)arg);
sockCount ++;
pthread_mutex_unlock(&m_read);
char ret [ 10 ];
printf("accept sock count is : %d !\n",sockCount);
usleep ( 100000 ) ;
strcpy ( ret ,"ok" );
send ( fd, ret, strlen (ret ), 0);//blocked when sockCount reach to 32571..
printf ("send ok ..\n");
close (fd);
pthread_exit(NULL);
}
~