7

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

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

3 回答 3

5

您无需更改所有新套接字的默认超时,而是只需设置该特定连接的超时即可。不过这个值有点低,所以把它增加到 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)
于 2012-12-15T04:22:35.220 回答
0

将 192.168.95.148 更改为 127.0.0.1(localhost - 连接到您自己)并在同一台机器上运行此程序。这样你就有了连接的东西。

于 2014-08-13T18:09:38.253 回答
0

它是一个假地址,我认为如果你想让它工作,你正在阅读暴力 python,输入socket.gethostname()而不是 假 IP地址,它将连接到你的机器。这是我的代码:

    def Socket_to_me(ip,port,time):
        try:
            s = socket.socket()
            s.settimeout(time)
            s.connect((ip,port))
            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) 

call the method by:
Socket_to_me(socket.gethostname(),1234,10)
于 2020-07-16T15:24:19.660 回答