我在这方面相当天真。我不确定为什么我的连接超时。提前谢谢。
#!/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
答案 0 :(得分:2)
您无需更改所有新套接字的默认超时,而只需设置该特定连接的超时即可。虽然值有点低,但是将其增加到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)
答案 1 :(得分:0)
将192.168.95.148更改为127.0.0.1(localhost - 连接到您自己)并在同一台计算机上运行this program。这样你就可以连接到。
答案 2 :(得分: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)