python socket.connect – >为什么会超时?

在这方面我很天真.我不确定为什么我的连接超时.提前致谢.

#!/usr/bin/env python
import socket

def socket_to_me():
    socket.setdefaulttimeout(2)
    s = socket.socket()
    s.connect(("192.168.95.148",21))
    ans = s.recv(1024)
    print(ans)

此代码生成的跟踪回溯

Traceback (most recent call last):
  File "logger.py", line 12, in <module>
    socket_to_me()
  File "/home/drew/drewPlay/python/violent/networking.py", line 7, in socket_to_me
    s.connect(("192.168.95.148",21))
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
timeout: timed out

最佳答案 您无需更改所有新套接字的默认超时,而只需设置该特定连接的超时即可.虽然值有点低,但是将其增加到10-15秒有望成功.

首先,这样做:

s = socket.socket()

然后:

s.settimeout(10)

你应该在连接上使用“try:”,并添加:

except socket.error as socketerror:
    print("Error: ", socketerror)

这将在输出中显示系统错误消息并处理异常.

修改后的代码版本:

def socket_to_me():
    try:
        s = socket.socket()
        s.settimeout(2)
        s.connect(("192.168.95.148",21))
        ans = s.recv(1024)
        print(ans)
        s.shutdown(1) # By convention, but not actually necessary
        s.close()     # Remember to close sockets after use!
    except socket.error as socketerror:
        print("Error: ", socketerror)
点赞