import struct

import zmq
from zmq.eventloop import ioloop

class TcpSubscriber:
	hdrfmt = struct.Struct('>I')

	def __init__(self, endpoint):
		self.connect(endpoint)
		self.reset()

	def connect(self, endpoint):
		zctx = zmq.Context.instance()
		zsock = zctx.socket(zmq.STREAM)
		zsock.connect(endpoint)
		myid = zsock.getsockopt(zmq.IDENTITY)

		io_loop = ioloop.IOLoop.instance()
		io_loop.add_handler(zsock, self.handle_read, io_loop.READ)

	def reset(self):
		self.wait_hdr = True
		self.packet_size = self.hdrfmt.size
		self.accum_buffer = bytearray()

	def handle_read(self, zsock, events):
		msgid = zsock.recv()
		payload = zsock.recv()
		if payload:
			self.accum_buffer.extend(payload)			
		else:		
			print "empty message!"
			self.reset()

		while len(self.accum_buffer) >= self.packet_size:
			pkt = buffer(self.accum_buffer, 0, self.packet_size)
			self.accum_buffer = bytearray(self.accum_buffer[self.packet_size:])
			if self.wait_hdr:
				self.wait_hdr = False
				self.packet_size = self.hdrfmt.unpack(pkt)[0]
			else:
				self.wait_hdr = True
				self.packet_size = self.hdrfmt.size
				self.handle_msg(pkt)

	def handle_msg(self, msg):
		print 'msgsize: {0}'.format(len(msg))

class MySubscriber(TcpSubscriber):
	def handle_msg(self, msg):
		idx = struct.unpack('I', msg[:4])[0]
		print '{0}: {1}'.format(idx, len(msg))

MySubscriber("tcp://127.0.0.1:10000")
io_loop = ioloop.IOLoop.instance()
io_loop.start()


@@ -136,16 +136,56 @@
 point):%0A
+%09%09self.reset()%0A%09%09self.connected = False%0A
 %09%09self.c
@@ -200,31 +200,16 @@
 ndpoint)
-%0A%09%09self.reset()
 %0A%0A%09def c
@@ -665,21 +665,26 @@
 .recv()%0A
+%0A
 %09%09if 
+not 
 payload:
@@ -691,95 +691,193 @@
 %0A%09%09%09
-self.accum_buffer.extend(payload)%09%09%09%0A%09%09else:%09%09%0A%09%09%09print %22empty message!%22%0A%09%09%09self.reset(
+if not self.connected:%0A%09%09%09%09self.handle_connect()%0A%09%09%09%09self.connected = True%0A%09%09%09else:%0A%09%09%09%09self.handle_disconnect()%0A%09%09%09%09self.connected = False%0A%09%09%09return%0A%0A%09%09self.accum_buffer.extend(payload
 )%0A%0A%09
@@ -1225,16 +1225,16 @@
 mt.size%0A
-
 %09%09%09%09self
@@ -1247,24 +1247,144 @@
 e_msg(pkt)%0A%0A
+%09def handle_connect(self):%0A%09%09print 'connect'%0A%09%09pass%0A%0A%09def handle_disconnect(self):%0A%09%09print 'disconnect'%0A%09%09self.reset()%0A%0A
 %09def handle_

interpret empty payload as connect/disconnect events