python socket.connect -> 为什么超时?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13889246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:51:40  来源:igfitidea点击:

python socket.connect -> timed out why?

pythonsockets

提问by Drew Verlee

I'm fairly naive in this regard. I'm not sure why my connection is timing out. Thanks in advance.

在这方面,我相当天真。我不确定为什么我的连接超时。提前致谢。

#!/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)

the trace back generated by this code

此代码生成的回溯

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

采纳答案by Aleksander S

You don't need to alter the default timeouts for all new sockets, instead you can just set the timeout of that particular connection. The value is a bit low though, so increasing it to 10-15 seconds will hopefully do the trick.

您不需要更改所有新套接字的默认超时,而只需设置该特定连接的超时即可。不过该值有点低,因此将其增加到 10-15 秒有望成功。

First, do this:

首先,这样做:

s = socket.socket()

Then:

然后:

s.settimeout(10)

And you should use "try:" on the connect, and add:

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

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

This will bring up the systems error message in your output and handle the exception.

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

Modified version of your code:

您的代码的修改版本:

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)

回答by Charles Noon

Change 192.168.95.148 to 127.0.0.1 (localhost - connecting to yourself) and run this programon the same machine. That way you'll have something to connect to.

将 192.168.95.148 更改为 127.0.0.1(本地主机 - 连接到自己)并在同一台机器上运行此程序。这样你就可以连接一些东西。