如何在等待接收数据时关闭阻塞套接字? [英] how to close a blocking socket while it is waiting to receive data?

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

问题描述

我有一个使用阻塞套接字接收数据的服务.我遇到的问题是,如果套接字仍在等待数据,我不知道如何正确关闭它.下面是我如何打开和等待数据的简短片段:我不想实现超时,因为根据 python 文档,套接字必须阻塞才能使用 makefile.

I have a service that uses a blocking socket to receive data. The problem I have is that I do not know how to properly close the socket if it is still waiting for data. Below is a short snip of how I am opening and waiting for data: I do not want to implement timeouts as according to the python documentation the socket must be blocking in order to use makefile.

我可能完全错误,因为我是使用套接字编程的新手.

I may be going about this completely wrong as I am new to programming with sockets.

应该注意的是,我不能改变服务器的运行方式.

It should be noted that the I cannot alter how the server operates.

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
reader = s.makefile("rb")
line = reader.readline()

推荐答案

关闭此套接字的一种解决方案是要求服务器关闭它.

One solution to close this socket is to ask the server to close it.

如果服务器关闭客户端socket,客户端会收到Connection reset by peer"错误,可能会中断接收.

If server close the client socket, the client will receive a "Connection reset by peer" error, and it may break the blocking receive.

另一种解决方案是不使用 readline() 并在您的套接字上设置超时(无限期等待....无限期)

Another solution would be to not use readline() and put a timeout on your socket (indefinite wait could wait.... indefinitely)

这篇关于如何在等待接收数据时关闭阻塞套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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