当远程服务器在读取完成之前关闭套接字时,如何处理C中的套接字读取? [英] How to handle socket read in C when the remote server closes socket possibly before read is finished?

查看:297
本文介绍了当远程服务器在读取完成之前关闭套接字时,如何处理C中的套接字读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

客户端阻塞读取调用,等待读取n个字节。

Client blocks on the read call waiting to read n bytes.

服务器写入n个字节,并立即关闭连接。

Server writes n bytes and closes the connection immediately.

在这种情况下,如果套接字在读取完成之前关闭或由于一些其他问题,可以读取调用返回否定或零? (在这种情况下,客户端/服务器在相同的linux框上运行)

Can read call return negative or zero in this case if the socket gets closed before read is finished or due to some other issue? (client/server running on same linux box in this case)

我面临这样的情况,但不知道这在TCP / IP子系统如何工作,

I am facing such a scenario but not sure how this works in TCP/IP subsystem and how to resolve it.

Sever:
write
close

Client:
read
close


推荐答案

关闭一个套接字连接首先调用shutdown表示不会被写入,继续读取远程端发送的数据,然后关闭读取端并关闭套接字。如果在读取发送给您的数据之前关闭套接字,操作系统将重置连接(发送一个RST标志置位的数据包),并且远程端将此解释为错误。

The safe way to close a socket connection is first calling shutdown to signal that you won't be writing, keep reading the data that the remote side sends, and then shutdown the reading side and close the socket. If you close the socket before reading data sent to you the OS resets the connection (sends a packet with the RST flag set) and the remote side interprets this as an error.

这篇关于当远程服务器在读取完成之前关闭套接字时,如何处理C中的套接字读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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