我想设置连接的最大值。如果它超过最大值,请告诉客户端现在服务器已满并关闭套接字。
如何用C编写代码?
谢谢。
答案 0 :(得分:10)
简单。在您拨打accept()
的时候,就像这样:
new_conn = accept(listen_sock, &addr, addr_len);
if (new_conn > 0)
{
if (total_connections < max_connections)
{
total_connections++;
register_connection(new_conn);
}
else
{
send_reject_msg(new_conn);
close(new_conn);
}
}
(当然,在您失去连接时会减少total_connections
。)
答案 1 :(得分:0)
嗯,你可以从我的书签开始使用tutorial。
您可以检查函数int listen(int sockfd, int backlog);
的第二个参数。
sockfd is the usual socket file descriptor from the socket() system call.
backlog is the number of connections allowed on the incoming queue. What
does that mean? Well, incoming connections are going to wait in this queue
until you accept() them (see below) and this is the limit on how many can
queue up. Most systems silently limit this number to about 20; you can
probably get away with settingit to 5 or 10