Python套接字连接超时 [英] Python socket connection timeout

查看:59
本文介绍了Python套接字连接超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个套接字,我想在连接时超时,以便在无法连接的情况下取消整个操作,但它也想将 makefile 用于不需要超时的套接字.

I have a socket that I want to timeout when connecting so that I can cancel the whole operation if it can't connect yet it also want to use the makefile for the socket which requires no timeout.

有没有简单的方法可以做到这一点,还是很难做到?

Is there an easy way to do this or is this going to be a difficult thing to do?

python 是否允许在连接后重置超时,以便我可以使用 makefile 并且仍然有套接字连接的超时

Does python allow a reset of the timeout after connected so that I can use makefile and still have a timeout for the socket connection

推荐答案

你只需要使用 socket settimeout() 方法在尝试 connect() 之前,请注意连接后必须 settimeout(None) 将套接字设置为阻塞模式,这是 makefile 所必需的.这是我正在使用的代码:

You just need to use the socket settimeout() method before attempting the connect(), please note that after connecting you must settimeout(None) to set the socket into blocking mode, such is required for the makefile . Here is the code I am using:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(address)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)

这篇关于Python套接字连接超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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