Python扭曲了长数据

时间:2013-04-25 14:46:33

标签: python networking twisted

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()

1 个答案:

答案 0 :(得分: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