コード例 #1
0
ファイル: topicserver.py プロジェクト: ddcatgg/dglib
	def connectionMade(self):
		self.host = self.transport.getPeer().host
		self.port = self.transport.getPeer().port
		self.serverport = self.transport.getHost().port
		self.introduction = self.factory.introduction
		self.option = self.factory.option
		self.debug = self.option["log"] not in [None, False, 0]
		self.notifiers = self.factory.notifiers

		self.login_ok = False
		self.subscribed_topics = set()

		if self.debug:
			v = self.option["log"]
			kw = v.copy() if isinstance(v, dict) else {}
			if kw.get("name") is None:
				kw["name"] = "TopicServer%d" % self.serverport
			if kw.get("subtitle") is None:
				kw["subtitle"] = "(%s-port%d)" % (self.host, self.port)
			self.tracer = Tracer2(**kw)
			self.tracer.info("connected from %s:%d" % (self.host, self.port))

		self.handler = HttpHandler(self)
		self.handler.package_received_event.add_listener(self.on_package_received)

		self.setTimeout(self.option["timeout"])
コード例 #2
0
ファイル: topicclient.py プロジェクト: ddcatgg/dglib
	def build_handler(self, prop):
		handler = HttpHandler(prop)
		return handler
コード例 #3
0
ファイル: topicserver.py プロジェクト: ddcatgg/dglib
class TopicServerProtocol(protocol.Protocol, TimeoutMixin):

	def __repr__(self):
		return "<TopicServerProtocol %s:%d server_port=%d>" % \
			(self.host, self.port, self.serverport)

	def connectionMade(self):
		self.host = self.transport.getPeer().host
		self.port = self.transport.getPeer().port
		self.serverport = self.transport.getHost().port
		self.introduction = self.factory.introduction
		self.option = self.factory.option
		self.debug = self.option["log"] not in [None, False, 0]
		self.notifiers = self.factory.notifiers

		self.login_ok = False
		self.subscribed_topics = set()

		if self.debug:
			v = self.option["log"]
			kw = v.copy() if isinstance(v, dict) else {}
			if kw.get("name") is None:
				kw["name"] = "TopicServer%d" % self.serverport
			if kw.get("subtitle") is None:
				kw["subtitle"] = "(%s-port%d)" % (self.host, self.port)
			self.tracer = Tracer2(**kw)
			self.tracer.info("connected from %s:%d" % (self.host, self.port))

		self.handler = HttpHandler(self)
		self.handler.package_received_event.add_listener(self.on_package_received)

		self.setTimeout(self.option["timeout"])

	def connectionLost(self, reason=protocol.connectionDone):
		if self.debug: self.tracer.info("disconnected\n")

		# 解除订阅
		for topic in self.subscribed_topics:
			notifier = self.notifiers.get(topic)
			if notifier:
				notifier.remove_subscriber(self)

	def dataReceived(self, data):
		if self.debug: self.tracer.debug("recv(%d bytes): %s\n" % (len(data), data.replace("\r\n", "\n")))

		self.handler.handle_data(data)

	def on_package_received(self, sender, package):
		self.resetTimeout()

		if not self.login_ok:
			if package.method == "GET" and package.path == "/Login":
				self.process_login(package)
			else:
				self.disconnect()
		else:
			if package.method == "SUBSCRIBE":
				self.process_subscribe(package)
			elif self.subscribed_topics:
				if package.method in ("GET", "POST"):
					self.process_common_request(package)
				else:	# 无效命令
					self.disconnect()
			else:	# 尚未订阅
				self.disconnect()

	def process_login(self, package):
		username = package.param.get("username", "")
		password = package.param.get("password", "")
		if username == "admin" and password == "admin":
			self.login_ok = True
			heads = [("Content-Type", "text/xml")]
			content = self.introduction
			self.send_response(heads=heads, content=content)
		else:
			self.disconnect()

	def process_subscribe(self, package):
		'''
		/Subscribe?objects=
		'''
		topics_s = package.param.get("objects", "")
		if topics_s:
			response = self.handler.make_response(200)
			self.send(response)
			topics = topics_s.split("|")
			if "*" in topics:
				topics = self.notifiers.keys()	# 订阅所有主题
			self.subscribe(topics)
		else:
			response = self.handler.make_response(400)
			self.send(response)

	def subscribe(self, topics):
		if self.subscribed_topics != topics:
			self.unsubscribe()
			self.subscribed_topics = topics
			for topic in topics:
				notifier = self.notifiers.get(topic)
				if notifier:
					notifier.add_subscriber(self)
					data = notifier.make_notify()
					if data is not None:
						self.send_notify(data)

	def unsubscribe(self):
		for topic in self.subscribed_topics:
			self.notifiers.remove_subscribe(topic)
		self.subscribed_topics = ""

	def process_common_request(self, package):
		# "/UpdateDevicesXml" -> "hreq_updatedevicesxml"
		processor_name = "hreq" + package.path.replace("/", "_").lower()
		path_processor = getattr(self, processor_name, None)
		if path_processor:
			path_processor(package)
		else:
			if self.debug: self.tracer.error("*** error! request handler not exists: %r" % path_processor)
			self.send_response(404)

	def send(self, s):
		if self.debug: self.tracer.debug("send(%d bytes): %s\n" % (len(s), s.replace("\r\n", "\n")))
		self.transport.write(s)

	def send_notify(self, s):
		self.send(self.handler.make_request("NOTIFY", path="/", content=s))

	def send_response(self, response_code=200, heads=[], content=""):
		self.send(self.handler.make_response(response_code, heads, content))

	def disconnect(self):
		self.transport.loseConnection()

	def timeoutConnection(self):			# 重载的超时方法
		self.transport.abortConnection()	# 如果不重载默认是loseConnection()