に、私はツイストでチャットサーバを書いていると私は理解broacastMessage(で問題を抱えている)方法:broadcastMessageツイストチャットサーバ
def broadcastMessage(self, message):
print list(self.factory.users.iteritems())
for name, protocol in self.factory.users.iteritems():
if protocol != self:
protocol.sendLine(message)
私はiteritems()を知るには、タプルを得なければなりません、例えば('Roman', <__main__.ChatProtocol instance at 0x7fc80b8b67a0>)
である。今度はこのタプルnames
とprotocols
を反復処理するときに、がself
インスタンスでない場合は、それを送信したユーザーのメッセージを印刷したくないという単純な理由があります。 (私はこの権利を得ていますか?)
それは動作すると期待していますが、それは何らかの理由ではありません。ここでコードです:
from twisted.internet import protocol, reactor
from twisted.protocols.basic import LineReceiver
class ChatProtocol(LineReceiver):
def __init__(self, factory):
self.factory = factory
self.name = None
self.state = "REGISTER"
def connectionMade(self):
self.sendLine("What's your name?")
def connectionLost(self, reason):
if self.name in self.factory.users:
del self.factory.users[self.name]
self.broadcastMessage("%s has left the channel." % (self.name,))
def lineReceived(self, line):
if self.state == "REGISTER":
self.handle_REGISTER(line)
else:
self.handle_CHAT(line)
def handle_REGISTER(self, name):
if name in self.factory.users:
self.sendLine("Name taken, please choose another.")
return
self.sendLine("Welcome, %s!" % (name,))
self.broadcastMessage("%s has joined the channel." % (name,))
self.name = name
self.factory.users[name] = self
self.state = "CHAT"
def handle_CHAT(self, message):
message = "<%s> %s" % (self.name, message)
self.broadcastMessage(message)
def broadcastMessage(self, message):
for name, protocol in self.factory.users.iteritems():
if protocol != self:
protocol.sendLine(message)
class ChatFactory(protocol.Factory):
def __init__(self):
self.users = {}
def buildProtocol(self, addr):
return ChatProtocol(self)
reactor.listenTCP(8000, ChatFactory())
reactor.run()
は、そしてここ端末セッションです:
(venv) [email protected] ~/Documents/learning/twisted/chat_server $ telnet localhost 8000
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
What's your name?
Roman
Welcome, Roman!
P.S:私がメッセージを送信するためにTelnetのを使用していますが。