我正在使用 ethernet enabled relay 。尝试通过套接字与 python 进行通信。我看到了非常有趣的行为,但我认为这与设备无关。下面是失败的代码。我收到的错误是 [Errno 22] Invalid argument
self.ip_addr = <some address>
self.port = <some port>
self.max_attempt_cnt = <some count>
self.sleep_interval = <some interval>
try_cnt=0
skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
try:
skt.connect((self.ip_addr, int(self.port)))
break
except socket.error as e:
try_cnt+=1
if (self.max_attempt_cnt > 0) and (try_cnt > self.max_attempt_cnt):
msg = 'Maximum connection attempt count of {} is exceeded'.format(
self.max_attempt_cnt
)
raise ConnectionAttemptCountExceededError(msg)
time.sleep(self.sleep_interval)
<do stuff 0>
<do stuff 1>
<do stuff 2>
如果我将 skt
的定义移到 while
循环内,即如下所示:
while True:
try:
skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
skt.connect((self.ip_addr, int(self.port)))
break
问题消失。
我知道有一种不同的方式来编写这段代码,但这不是我要问的。
我的问题是为什么当在循环外部创建套接字时代码会失败以及为什么当在循环内部创建套接字时代码会起作用?
编辑
我意识到我没有提到这段代码可以在 Windows
上运行,但它不能在 Mac
机器上运行,这就是我的意思使用。
最佳答案
来自 Linux (debian/Jessie) 附带的 connect
手册页
If
connect()
fails, consider the state of the socket as unspecified. Portable applications should close the socket and create a new one for reconnecting.
基于此,无效参数错误消息指的是与不处于可用状态的套接字对应的给定文件描述符。
关于python套接字,无效参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43643876/