您无需更改所有新套接字的默认超时,而只需设置该特定连接的超时即可.虽然值有点低,但是将其增加到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)