我正在做 Cesare Rocchi 的教程“如何创建基于套接字的 iPhone 应用程序和服务器” http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server#注释
我是否需要在“class IphoneChat(Protocol)”中定义一个名为“name”的属性,还是从“twisted.internet.protocol”继承?如果它是继承的,我该如何正确访问它?
服务器.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 的类定义,发现没有像“名称”这样的东西http://twistedmatrix.com/documents /11.0.0/api/twisted.internet.protocol.Protocol.html
- 从我在其他地方读到的内容来看,这可能只是一个缩进错误。