How to transport an object in a twisted?

I know with "transport.write ()" I can pass a string object, but I want to know if it is possible to transfer data of another type, something like an object of class python? if possible, how can i do this?

+4
source share
3 answers

You can create an arbitrary user protocol, but it can be more productive to use a framework that already exists for this purpose, for example, google protocol buffers , which allow you to easily determine the effective structure of message passing and already support python.

JSON is a lightweight alternative, and many people simply use zipped json objects because it is easy and built into python by default, but the results are slow, have unpredictable size artifacts (zipped is usually larger than the uncompressed output for numerous small messages) and are bad binary data transfer solution.

Edit: Oh yes, and don't use pickle.

+2
source

You can use json to serialize objects. Almost all Python objects are serializable json, and if not, you can write your own encoder-decoder to process them. Do not use eval to decode input.

+2
source

. , python .

, , python, , , , Ashwini , pickle, ,

import pickle 
from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet import reactor
from twisted.internet.endpoints import TCP4ClientEndpoint


class ClassSender(Protocol):

    def dataReceived(self, data):
        print pickle.loads(data)

    def writeObject(self, _object):
        pickle.dump(_object,self.transport)


class ClassSenderFactory(ClientFactory):
    def buildProtocol(self, addr):
        return ClassSender()

class MyClass(object):
   def __init__(self,data):
       self.data = data

def SendObject(protocol):
    print "Sending"
    protocol.writeObject(MyClass('some sample data'))


point = TCP4ClientEndpoint(reactor, "localhost", 8000)
d = point.connect(ClassSenderFactory())
d.addCallback(SendObject)

reactor.run()

8000 (localhost) TCP. , , .

, , .

, (http://twistedmatrix.com/documents/current/core/examples/echoserv.py) , get -.

The problem is that many angular cases must be taken into account. What if the data is divided into two blocks, so we can’t unlock it with one call? Fortunately, twisted provides a ready-made class for working with this so-called promising broker. If you control both ends of the wire, this can solve many of these problems for you. Take a look at: https://twistedmatrix.com/documents/12.2.0/core/howto/pb-intro.html

-2
source

All Articles