【问题标题】:Python Twisted for long dataPython Twisted 长数据
【发布时间】:2013-04-25 14:46:33
【问题描述】:

Python 编码员

我正在使用 twisted 构建一个服务器,它在每个连接上接收 3000 字节的数据,我的问题是包被截断并存储在数据库中,就像包块一样,我正在寻找的是一种方法解决这类数据包必须解析为一个长数据的问题。

收到的行不是一种方式,因为这种数据是在没有分隔符的情况下发送的,然后我正在考虑一种循环方式,但是我不完全确定它或如何实现

from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
import binascii
from Datagram import *

class LingServer(Protocol):


    def __init__(self):
        print 'Staring Ling Server'
        pass

    def connectionMade(self):
        try:
            print 'Accepted connection'
        except ValueError:
            print "Oops!  Connection was not started"

    def connectionLost(self, reason):
        print "Connection lost ", reason  

    def dataReceived(self, data):
        try:
            print "Data received ", data
            data = binascii.hexlify(data)
            Datagram (header=data[:10], content=data[10:])
            session.commit()

            #self.transport.write(self.decoder.processDatagram(data))
        except ValueError:
            print "Oops!  That was no valid data.  Try again..."


class LingFactory(Factory):  

    def __init__(self):
        pass

    def buildProtocol(self, addr):
        return LingServer()

reactor.listenTCP(12345, LingFactory())
reactor.run()

【问题讨论】:

    标签: python networking twisted


    【解决方案1】:

    TCP 是面向流的。见the FAQ entry for this topic

    如果您想在处理前缓冲 3000 字节,请参阅twisted.protocols.stateful.StatefulProtocol。例如:

    class LingServer(StatefulProtocol):
        def getInitialState(self):
            return self.ling, 3000
    
        def ling(self, data):
            # Process here, len(data) == 3000
    

    【讨论】:

      猜你喜欢
      • 2011-02-12
      • 2010-10-02
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 2013-01-19
      • 2011-06-11
      相关资源
      最近更新 更多