具有recv-timeout的套接字:此代码有什么问题? [英] Socket with recv-timeout: What is wrong with this code?

查看:128
本文介绍了具有recv-timeout的套接字:此代码有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个Recv超时为1秒的套接字:

I'm trying to implement a socket with a recv timeout of 1 Second:

int sockfd;
struct sockaddr_in self;
struct sockaddr_in client_addr;
int addrlen=sizeof(client_addr);
ssize_t nBytes;

sockfd = socket(AF_INET, SOCK_STREAM, 0);

self.sin_family = AF_INET;
self.sin_port = htons(PORT);
self.sin_addr.s_addr = INADDR_ANY;

int on = 1;
setsockopt( sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on);

// 1 Sec Timeout
tv.tv_sec  = 1;  
tv.tv_usec = 0;
setsockopt( sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv);

bind(sockfd, (struct sockaddr*)&self, sizeof(self));

listen(sockfd, 20);

clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &addrlen);

nBytes = recv(clientfd, buffer, MAXBUF-1, 0);

没有'setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,& tv,sizeof(tv);')接受和接收的调用有效,但是recv阻止.

Without 'setsockopt( sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv);' the calls to accept and recv work, but recv blocks.

使用'setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,& tv,sizeof(tv);')的调用会产生错误'资源暂时不可用'.

With 'setsockopt( sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv);' the call to accept produces the error 'Resource temporarily unavailable'.

有人可以告诉我这种方法有什么问题吗?

Can somebody please tell me what is wrong with this approach?

推荐答案

您要在哪个套接字上启用一秒超时?一个接受连接,还是一个由accept()建立的连接?

Which socket do you want to have the one-second timeout on? The one accepting connections, or the one established by accept()?

我假设是后者-因此请在接受返回后尝试在clientfd上设置接收超时.您还可以到达需要使用select的位置,但不必这样做.

I'd assume the latter - so try setting the receive timeout on clientfd AFTER the accept returns. You can also get to where you need to be using select, but you shouldn't need to.

这篇关于具有recv-timeout的套接字:此代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆