我试图测试监听积压限制。我收集有关这方面的信息已有好几天了,我知道提供给listen()的积压号码只是一个提示。但现在我正在尝试创建一个服务器和一个客户端(使用TCP)来测试积压的限制。
在我的服务器上,我使用connect(),bind()和listen()然后sleep()很长一段时间。 在我的客户端,我使用一个创建fdsock的循环并使用connect()。
服务器不接受任何事情,所以我认为连接会进入积压队列,但程序永远不会停止,即使已经包装了超过1000个sockfd。
有没有办法测试积压队列最大限制?
先谢谢。
编辑:
#include "sys.h"
char *answer(char *port, int (*fun)(int)){
struct addrinfo * info, * p, indices;
struct sockaddr fromaddr;
int fd, t, toclient;
unsigned int len = sizeof fromaddr;
memset(&indices, 0, sizeof indices);
indices.ai_flags = AI_PASSIVE;
indices.ai_family = AF_INET;
indices.ai_socktype = SOCK_STREAM;
t = getaddrinfo(0, port, &indices, &info);
if(t != 0)
{
return "answer: cannot get info on port";
}
for(p = info; p != 0; p = p->ai_next)
{
fd = socket(p->ai_family, p->ai_socktype, 0); // fabriquer la socket
if(fd >= 0)
{
break;
}
}
if(p == 0)
{
return "answer: cannot open socket";
}
t = 1;
t = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &t, sizeof t);
if(t < 0)
{
perror("setsockopt");
}
if(bind(fd, p->ai_addr, p->ai_addrlen) < 0)
{
close(fd);
return "answer: cannot bind socket";
}
freeaddrinfo(info);
t = listen(fd, 1);
if(t < 0)
{
close(fd);
return "answer: cannot listen on socket";
}
for(;;)
{
toclient = accept(fd, &fromaddr, &len);
sleep(600);
if(toclient < 0)
{
return "answer: cannot accept\n";
}
t = fork();
if(t < 0) // error
{
perror("fork");
continue;
}
else if(t != 0) // parent
{
close(toclient);
}
else // child
{
close(fd);
fun(toclient);
exit(0);
}
}
}
int foo(int n){
char c;
int t;
printf("I have a new client\n");
while((t = read(n, &c, 1)) > 0)
{
if(write(n, &c, 1) != 1)
{
perror("write");
break;
}
}
if(t < 0)
{
perror("read");
}
printf("I don't have that client anymore\n");
return 0;
}
int main(int argc, char *argv[]){
char *p;
p = answer(argv[1], foo);
perror(p);
return 1;
}
这是我客户的代码:
# include "sys.h"
int dial(char *machine, char *port){
struct addrinfo *info, *p, indices;
int toserver, t;
memset(&indices, 0, sizeof indices);
indices.ai_family = AF_INET;
indices.ai_socktype = SOCK_STREAM;
t = getaddrinfo(machine, port, &indices, &info);
if(t != 0)
{
return -1;
}
for(p = info; p != 0; p = p->ai_next)
{
toserver = socket(p->ai_family, p->ai_socktype, 0);
if(toserver >= 0)
{
break;
}
}
if(p == 0)
{
return -1;
}
t = connect(toserver, info->ai_addr, info->ai_addrlen);
if(t < 0)
{
freeaddrinfo(info);
close(toserver);
return -1;
}
freeaddrinfo(info);
return toserver;
}
int main(int argc, char *argv[]){
char buffer[1];
int t, fd = dial(argv[1], argv[2]);
while((t = read(0, buffer, sizeof buffer)) > 0)
{
write(fd, buffer, t);
t = read(fd, buffer, sizeof buffer);
write(1, buffer, t);
}
return 0;
}
我将待办事项长度设置为1,然后我让服务器长时间休眠,这样我就可以尝试启动一些客户端,但即使我启动了数百个客户端,他们仍然不会拒绝。