使用扭曲的框架将文件发送到客户端

时间:2014-09-10 11:47:54

标签: python twisted

我一直在搜索如何使用扭曲的框架将文件从服务器传输到客户端一段时间,但我还没有找到任何有用的东西。

在我的情况下,我只想为用户发送图像,它是一个聊天应用程序,我在本地存储[我有服务器的地方]图像[或者我正在尝试]

这是我做的:

from twisted.internet import reactor
from twisted.internet.protocol import Factory , Protocol
class IphoneChat(Protocol):
      def connectionMade(self):
            self.factory.clients.append(self)
      def connectionLost(self , reason):
            self.factory.clients.remove(self)
      def dataReceived(self,data):
            a = data.split(':')
            contor = 0
            command = a[0]
            content = a[1]
            if command == "saveimage":
                personName = a[1]
                contentData = a[2]
                escape = a[3]
                location = "person-images/"+str(personName)+".jpg"
                try:
                    f = open (location,'w+')
                    f.write(contentData)
                except :
                    self.transport.write("error when opening the file")
            elif command == "getimage" :
                picture = a[1]
                extra = a[2]
                location = "person-images/"+picture+".png"
                try:
                    self.transport.write("image:")
                    for bytes in read_bytes_from_file(location) :
                        self.transport.write(bytes)
                    self.transport.write('\r\n')
                except :
                    self.transport.write('no such file\r\n')

factory = Factory()
factory.protocol=IphoneChat
factory.clients = []
reactor.listenTCP(8023,factory)
print "IPhone Chat server started"
reactor.run()

但是我在客户端[iOS应用程序]遇到了一个奇怪的行为,并且行为是它无法正常工作。

来自iosApp的东西:

                            var binaryData: NSData
                            let string : NSString  = output.componentsSeparatedByString(":")[0] as NSString
                            binaryData = string.dataUsingEncoding(NSUTF8StringEncoding)!

                            var data = UIImage(data: binaryData)
                            self.personImage.image = data
                            self.personImage.hidden = true

问题出在服务器端还是客户端?

1 个答案:

答案 0 :(得分:4)

可以立即发现一个严重的错误,但是我不能说这是否是使它“无法正常工作”的唯一因素:您的代码期望当一端为transport.write(x)时,另一端为dataReceived(self, x) x 1}} transport.write('foobar')调用是相同的。 TCP通常不是这种情况。 TCP提供了一个字节流,您无法控制流的分段方式。见Twisted FAQ。例如,如果一端有dataReceived('foob'),则另一端可能最终有两个电话:第一个dataReceived('ar')'\r\n'之后不久。

您需要做的是实现适当的协议,以便通过TCP流传递消息。但是,我建议不要自己滚动,而是选择Twisted中包含的几个中的一个,或者采用另一个明确指定的协议,例如websockets。

您似乎使用LineReceiver结束消息,这是一种在字节流中分隔消息的策略,但请注意,您需要在接收器上进行缓冲以收集完整的消息。这就是Twisted中包含的read_bytes_from_file()协议。但是,如果您的'\r\n'函数返回字符名称,如果图像数据包含字节dataReceived(x)

,则协议将中断

一些一般的开发建议:不要试图将完整的实现与扭曲的服务器和iPhone客户端放在一起,然后发现它不起作用。您可能在客户端和服务器上还有几个错误,但这只是预期的。编写可以在同一台机器上轻松测试的代码。那么,写一个简单的测试客户端就可以在服务器上运行。添加调试打印或日志记录以查看正在进行的操作,例如打印调用{{1}}的内容。

相关问题