我在Python 2.7中编写一个非常简单的udp套接字连接
服务器端已启动并正在运行。 我在客户端遇到麻烦。
from socket import *
serverName = '127.0.0.1'
serverPort = 5444
counter = 1;
while counter < 55:
mySocket = socket(AF_INET,SOCK_DGRAM)
try:
mySocket.settimeout(1.0)
message = raw_input('')
mySocket.sendto(message,(serverName, serverPort))
modifiedMessage, serverAddress = mySocket.recvfrom(1024)
except mySocket.timeout:
print 'Request timed out!'
mySocket.close()
else:
print 'Server Response: '
print modifiedMessage
mySocket.close()
我收到以下错误。 除了mySocket.timeout: AttributeError:'_socketobject'对象没有属性'timeout'
我无法理解为什么没有超时属性?!
事实上,我正在看知识分子,也没有这样的属性。
任何建议都将不胜感激
答案 0 :(得分:5)
socket
模块有一个timeout
类。您的套接字对象mysocket
(类型为socket.socket
)没有timeout
属性。
试试这个:
except timeout:
print 'Request timed out!'
mySocket.close()
请注意,以这种方式使用import *
也应该小心。
答案 1 :(得分:1)
我有python 2.7,它适用于ipython
Launching python -O
Python 2.7.2 (default, Apr 17 2012, 22:01:25)
Type "copyright", "credits" or "license" for more information.
IPython 0.13 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: from socket import *
In [2]: mySocket = socket(AF_INET, SOCK_DGRAM)
In [3]: mySocket.
mySocket.accept mySocket.dup mySocket.getsockopt mySocket.recv mySocket.sendall mySocket.shutdown
mySocket.bind mySocket.family mySocket.gettimeout mySocket.recv_into mySocket.sendto mySocket.type
mySocket.close mySocket.fileno mySocket.listen mySocket.recvfrom mySocket.setblocking
mySocket.connect mySocket.getpeername mySocket.makefile mySocket.recvfrom_into mySocket.setsockopt
mySocket.connect_ex mySocket.getsockname mySocket.proto mySocket.send mySocket.settimeout
In [3]: mySocket.
mySocket.accept mySocket.dup mySocket.getsockopt mySocket.recv mySocket.sendall mySocket.shutdown
mySocket.bind mySocket.family mySocket.gettimeout mySocket.recv_into mySocket.sendto mySocket.type
mySocket.close mySocket.fileno mySocket.listen mySocket.recvfrom mySocket.setblocking
mySocket.connect mySocket.getpeername mySocket.makefile mySocket.recvfrom_into mySocket.setsockopt
mySocket.connect_ex mySocket.getsockname mySocket.proto mySocket.send mySocket.settimeout
In [3]: mySocket.set
mySocket.setblocking mySocket.setsockopt mySocket.settimeout
In [3]: mySocket.set
mySocket.setblocking mySocket.setsockopt mySocket.settimeout
In [3]: mySocket.settimeout(1.0)
In [4]: