我做切薩雷羅基的教程「如何創建基於套接字的iPhone應用程序和服務器」 http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server#commentsexceptions.AttributeError:Python實例沒有屬性「名」
我需要定義一個名爲「名稱」中的一個屬性「IphoneChat類(協議)」還是繼承自「twisted.internet.protocol?」如果它是遺傳的,我如何正確訪問它?
server.py:
from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
class IphoneChat(Protocol):
def connectionMade(self):
self.factory.clients.append(self)
print "clients are", self.factory.clients
def connectionLost(self, reason):
self.factory.clients.remove(self)
def dataReceived(self, data):
a = data.split(':')
print a
if len(a) > 1:
command = a[0]
content = a[1]
msg = ""
if command == "iam":
self.name = content
msg = self.name + "has joined"
elif command == "msg":
msg = self.name + ": " + content
print msg
for c in self.factory.clients:
c.message(msg)
def message(self, message):
self.transport.write(message + '\n')
factory = Factory()
factory.protocol = IphoneChat
factory.clients = []
reactor.listenTCP(80, factory)
print "Iphone Chat server started"
reactor.run()
端子輸出:
Iphone Chat server started
...
--- <exception caught here> ---
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/selectreactor.py", line 150, in _doReadOrWrite
why = getattr(selectable, method)()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/tcp.py", line 199, in doRead
rval = self.protocol.dataReceived(data)
File "server.py", line 30, in dataReceived
msg = self.name + ": " + content
exceptions.AttributeError: IphoneChat instance has no attribute 'name'
解決問題到此爲止:
- 我讀了 「名」 是管理服務器端,在self.factory.clients列表,但後來我查找了twisted.internet.protocol的類定義,發現沒有任何內容像「name」http://twistedmatrix.com/documents/11.0.0/api/twisted.internet.protocol.Protocol.html
- 從我在其他地方看到的這可能只是一個縮進錯誤。
這是不是真的你的問題是什麼,但它是你的問題稍後會用這個代碼命中:請注意,您不能依賴'dataReceived'來傳遞整個消息。請參閱此常見問題解答:http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#Whyisprotocol.dataReceivedcalledwithonlylypartofthedataatacalledtransport.writewith – Glyph