我使用 reywenderlich http://www.raywenderlich.com/3932/的这个教程成功地创建了一个简单的聊天服务器
代码:
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
class IphoneChat(Protocol):
def connectionMade(self):
#self.transport.write("""connected""")
self.factory.clients.append(self)
print "clients are ", self.factory.clients
def connectionLost(self, reason):
self.factory.clients.remove(self)
def dataReceived(self, data):
#print "data is ", data
a = data.split(':')
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(79, factory)
print "Iphone Chat server started"
reactor.run()
基本上整个教程展示了一个聊天实现,用户加入一个特定的聊天室并互相实时聊天。但是我的客户想要一个点对点的聊天机制,用户可以选择一个特定的用户与之聊天,所以我真的不知道如何让它成为现实。我将衷心感谢您的帮助。谢谢