【发布时间】:2013-01-02 20:07:51
【问题描述】:
我用 Twisted 制作了这个服务器,它从客户端接收字符串并将其发送到所有其他连接的客户端。 但是有没有办法将字符串发送给发件人想要发送给的客户?如果是这样,我该如何在代码中做到这一点?这是我到目前为止所做的(注意我是 Python 中的一个完整的菜鸟。我只需要为我的 iOS 应用程序构建一个服务器,所以如果问题很愚蠢,我很抱歉):
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()
感谢您的帮助
【问题讨论】:
-
答案是:是的。谢谢。
-
什么?!?!我的问题很不一样
-
不,您的问题正是这样:“但是有没有办法将字符串发送给发送者想要发送给的客户端?”。答案就是这样:“yes”。请提出您想问的问题,告诉我们what have you tried(最好是代码sn-p等)。目前这并不是一个真正适合 StackOverflow 的问题(因此,就 Stack Overflow 而言,您的“问题”并不是真正的问题)。
-
@Tadeck 对不起,我的错。我改变了问题。
-
你能告诉我你是怎么解决这个问题的吗?
标签: python networking twisted