C / C ++插座和非阻塞的recv() [英] C/C++ sockets and a non-blocking recv()

查看:123
本文介绍了C / C ++插座和非阻塞的recv()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,即调用接收()系统调用不会阻塞。我此刻的客户端 - 服务器结构设置,我有问题我向服务器发送一个消息,在服务器设置,以便它是这样的:

I'm having a problem where calling recv() system call does not block. I have a client-server structure setup at the moment, and the problem I am having is I send the server one message, while the server is set up so that it's something like:

while (1) {
   char buf[1024];
   recv(fd, buf, sizeof(buf), flags);
   processMsg(buf);
}

有正确地接收到第一消息,但的recv()不阻塞和接收希望什么这不是垃圾数据。我想,只有当它们被发送到的信息作出响应。谁能指教?

It receives the first message correctly, but the recv() does not block and "receives" trash data which is not what is desired. I'd like to react to messages only when they are sent. Can anyone advise?

推荐答案

的recv()不一定阻塞,直到完整的请求得到满足,但可以返回部分请求。返回code会告诉你多少字节实际收到可以比你少要求。即使您指定MSG_WAITALL标志,可以少因回的信号,等等。

recv() does not necessarily block until the full request is fulfilled but can return a partial request. The return code will inform you of how many bytes were actually received which can be less than you requested. Even if you specify a MSG_WAITALL flag it can return less due to a signal, etc.

在POSIX系统,以阻塞模式的recv只会阻塞,直到,直到一些数据是present被读取。然后将返回的数据,其可以是小于要求的,最多要求的金额。在非阻塞模式的recv会立即返回,如果有零字节读取数据,并且将返回-1,设置errno为EAGAIN或EWOULDBLOCK。

On posix systems, in blocking mode recv will only block until until some data is present to be read. It will then return that data, which may be less than requested, up to the amount requested. In non-blocking mode recv will return immediately if there is zero bytes of data to be read and will return -1, setting errno to EAGAIN or EWOULDBLOCK.

其结果是,通常你会调用的recv在一个循环,直到你得到你想要的,同时还检查0返回codeS(对方断开)的金额或-1(一些错误)。

The upshot is that normally you will call recv in a loop until you get the amount you want while also checking for return codes of 0 (other side disconnected) or -1 (some error).

我不能到Windows行为说话。

I can't speak to windows behavior.

这篇关于C / C ++插座和非阻塞的recv()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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