从已经关闭的套接字接收数据? [英] Receiving data from already closed socket?

查看:76
本文介绍了从已经关闭的套接字接收数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个服务器应用程序-连接是通过UNIX套接字通过TCP进行的。

Suppose I have a server application - the connection is over TCP, using UNIX sockets.

该连接是异步的-换句话说,是客户端和服务器的套接字是非阻塞的。

The connection is asynchronous - in other words, clients' and servers' sockets are non-blocking.

假设以下情况:在某些情况下,服务器可能决定向连接的客户端发送一些数据并立即关闭连接:使用 shutdown SHUT_RDWR

Suppose the following situation: in some conditions, the server may decide to send some data to a connected client and immediately close the connection: using shutdown with SHUT_RDWR.

所以,我的问题是-是否可以保证客户端调用 recv ,它将接收(由服务器发送)数据吗?

So, my question is - is it guaranteed, that when the client call recv, it will receive the (sent by the server) data?

或者,要接收数据,必须在服务器 shutdown <之前调用 recv / code>?如果是这样,我应该怎么做(或更准确地说,我应该怎么做),以确保该数据被客户端接收?

Or, to receive the data, recv must be called before the server's shutdown? If so, what should I do (or, to be more precise, how should I do this), to make sure, that the data is received by the client?

推荐答案

您可以使用 setsockopt(SO_LINGER)控制此行为:

You can control this behavior with "setsockopt(SO_LINGER)":


  • man setsockopt

SO_LINGER
等待完成关闭功能(如果存在数据) 。启用此选项并且调用close
函数时没有未发送的数据时,在
close函数期间将阻止调用应用程序,直到数据传输或连接中的
超时为止。 close函数返回时不会阻塞调用方。
此选项仅对流套接字有意义。

SO_LINGER Waits to complete the close function if data is present. When this option is enabled and there is unsent data present when the close function is called, the calling application is blocked during the close function until the data is transmitted or the connection has timed out. The close function returns without blocking the caller. This option has meaning only for stream sockets.

另请参见:

Beej的网络编程指南

这篇关于从已经关闭的套接字接收数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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