簡體   English   中英

如何在扭曲的python中將列表從服務器發送到客戶端?

[英]How to send list from server to client in twisted python?

我在用python編寫多客戶端聊天服務器程序。 在我的程序中,如果我們從一個客戶端發送“列表”,則服務器必須將連接的客戶端列表發送到該客戶端。 同樣,當我們從一個客戶端發送“交談客戶端名稱消息”時,服務器必須將該消息發送到“客戶端名稱”中指定的目標客戶端。 但是我的代碼無法正常工作。 服務器中有錯誤。 不顯示列表,通話也不起作用。

我的服務器代碼如下:

class MultiEcho(Protocol):

    def __init__(self, factory):
        self.factory = factory

    def connectionMade(self):
        self.factory.clients.append(self)

    def dataReceived(self,data):
        data = data.strip()

        if (data == "list"):
            for client in self.factory.clients:
                print self.factory.clients
                self.transport.write(self.factory.clients)
        else:
            data = data.split()
                    if (len(data) > 1):
                l = data[1]
                m = data[2]
                l.transport.write(m)

    def connectionLost(self,reason):
        self.factory.clients.remove(self)       

class MultiEchoFactory(Factory):

    def __init__(self):
        self.clients = []
    def buildProtocol(self, addr):
        return MultiEcho(self)
if __name__ == '__main__':

    import sys
    if len(sys.argv) != 4:
        print "Sorry.. not correct.. Try Again!"
        sys.exit(1)
    else:
        if (sys.argv[1] == "chatserver") and (sys.argv[2] == "-p"):
            PORT = sys.argv[3]
    reactor.listenTCP(8000, MultiEchoFactory())
    reactor.run()   

有人可以給我解決辦法嗎

  • 您不能依靠dataReceived()接收多少數據。 您可能需要從LineReceiver子類,並使用lineReceived()處理輸入。
  • transport.write()接受字符串,而不是列表。

您需要定義clientname的客戶例如,工廠應該能夠找到它的名字的客戶機。 然后,您可以在LineReceived()

command, _, rest = line.partition(command_separator)
if command == "talk":
   clientname, _, message = rest.partition(arg_separator)
   self.factory.getClient(clientname).sendLine(message)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM