gpt4 book ai didi

python套接字文件读取超时?

转载 作者:行者123 更新时间:2023-12-01 06:08:30 29 4
gpt4 key购买 nike

我使用 python 套接字作为文件来与另一个进程通信:

def connect(self):
try:
self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect( (self.target, self.port) )
self.fobj = self.sock.makefile()

通常我会通过套接字编写命令并期望在一定时间内得到答复。所以我的问题是:有没有办法在从套接字文件对象读取一行时实现超时?

谢谢

最佳答案

取自 Python's documentation about socket.makefile() :

socket.makefile([mode[, bufsize]])

Return a file object associated with the socket. (File objects are described in File Objects.) The file object references a dup()ped version of the socket file descriptor, so the file object and socket object may be closed or garbage-collected independently. The socket must be in blocking mode (it can not have a timeout). The optional mode and bufsize arguments are interpreted the same way as by the built-in file() function.

因此,套接字文件上不能有超时,如果需要超时,则必须使用常规套接字。

关于python套接字文件读取超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6914161/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com