Twisted - 向选定的客户端发送数据 [英] Twisted - sending data to selected clients

查看:62
本文介绍了Twisted - 向选定的客户端发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Twisted 制作了这个服务器,它从客户端接收字符串并将其发送到所有其他连接的客户端.但是有没有办法将字符串发送给发件人想要发送的客户端?如果是这样,我如何在代码中做到这一点?这就是我到目前为止所做的(注意我是 Python 的完全菜鸟.我只需要为我的 iOS 应用程序构建一个服务器,所以如果问题很愚蠢,我很抱歉):

There is this server I made with Twisted which receives strings from a client and send it to all of the other connected clients. But is there a way to send the string to just clients that the sender wanted to send it to ? If so, how do I do it in code ? This is what I did so far (NOTE I am a complete noob in Python. I just need to build a server for my iOS app, so I am sorry if the question is silly):

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 = "iam" + self.name + " has joined"

            elif command == "msg":
                msg = self.name + ": " + content

            elif command == "img":
                msg = command + ":" + content + ":" + command

            elif command == "img2":
                msg = content

            elif command == "img3":
                msg = 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(53080, factory)
print "Iphone Chat server started"
reactor.run()

感谢您的帮助

推荐答案

self.factory.clients[24].transport.write("You are client 24!")

我觉得应该可以

这篇关于Twisted - 向选定的客户端发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆