According to twisted documentation a new Protocol instance is created every time a connection is made however i am observing some sort of data sharing between the two.
Briefly I have defined a class that each protocol will use for state
class JSONCollector():
char_buffer = StringIO.StringIO()
...
def process_data(self, data):
...
self.char_buffer.write(char)
The protocol instantiates it
class JSONProtocol(protocol.Protocol):
def __init__(self):
self.json_collector = JSONCollector()
def dataReceived(self, data):
self.json_collector.process_data(data)
self.transport.write(str(self))
However each connection seems to get the same instance of JSONCollector, when I added the following statements to dataReceived self.transport.write(str(self.json_collector.char_buffer)) self.transport.write(str(self))
I get the following:
connection 1: StringIO.StringIO instance at 0x968ae2c>< main .JSONProtocol instance at 0x969036c>
connection 2: StringIO.StringIO instance at 0x968ae2c>< main .JSONProtocol instance at 0x969068c>
Also everytime I type in text, text that was typed in from other connection(s) gets displayed. So it seems that for some strange reason StringIO() instances are shared, am I missing something. I suppose I can use a factory to separate buffers by addr and make sure each Protocol only uses its own buffer, but without having the need for shared storage I would rather not jump through hoops
Thank you.
This:
class JSONCollector():
char_buffer = StringIO.StringIO()
Seems like an error, and the source of your troubles. Instead, try this:
class JSONCollector():
def __init__(self):
self.char_buffer = StringIO.StringIO()
Otherwise, you are making one char_buffer
for the entire class type, as opposed to one per instance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.