Example #1
0
class SimulationServer:
	"""The handler of WebSockets based communications and creator of the sim pool."""
	def __init__(self):
		self.ws_server = WebSocketServer(self.ws_callback, port=settings.WEB_SOCKETS_PORT)
		self.sim_pool = sim_pool.SimulatorPool(self)
		self.ws_connections = []
		self.registration = None
		
	def start(self):
		self.sim_pool.start_all_spaces()
		self.ws_server.start()
		self.registration, created = SimulatorPoolRegistration.objects.get_or_create(ip=self.ws_server.sock.getsockname()[0], port=self.ws_server.port)

	def stop(self):
		if self.registration:
			try:
				self.registration.delete()
			except:
				traceback.print_exc()

		self.sim_pool.stop_all_spaces()
		self.ws_server.stop()
		
		for con in self.ws_connections:
			try:
				con.client_socket.shutdown(1)
			except:
				traceback.print_exc()

	def send_space_event(self, space_id, event):
		for connection in self.get_client_connections(space_id):
			connection.outgoing_events.put(event)

	def get_client_connections(self, space_id):
		#TODO keep a hashmap of space_id:connection[] for faster access
		cons = []
		for connection in self.ws_connections:
			if connection.space_id == space_id: cons.append(connection)
		return cons

	def ws_callback(self, client_socket):
		ws_connection = WebSocketConnection(client_socket, self)
		self.ws_connections.append(ws_connection)
		try:
			ws_connection.handle_incoming()
		except (IOError):
			ws_connection.finish()
Example #2
0
	def __init__(self):
		self.ws_server = WebSocketServer(self.ws_callback, port=settings.WEB_SOCKETS_PORT)
		self.sim_pool = sim_pool.SimulatorPool(self)
		self.ws_connections = []
		self.registration = None