import socket
import pickle

class ServerGame: 

	def __init__( self ):

		self.socket = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
		self.socket.setblocking( False )
		self.socket.bind( ( host, port ) )

		self.address_to_user = {}


	def start( self ):

		while True:

			data = self.receive()

			if len( data ):
				if "CHAR" in data:
					name = data["CHAR"].keys()[0]
				self.send( data, name )


	def receive( self ):
		try: 
			data, address = self.socket.recvfrom( 1024 )
			print address
			if not address in self.address_to_user:
				self.address_to_user[ address ] = "Player " + str( len( self.address_to_user ) + 1 ) 

			unpickled_data = pickle.loads( data )

			if "PLAYER_DATA" in unpickled_data:
				player = self.address_to_user[ address ]
				player_data = unpickled_data["PLAYER_DATA"]

				return {"CHAR": { player:player_data } }
			else:
				return {}

		except socket.error:
			return {}


	def send( self, data, name ):
		pickled_data = pickle.dumps( data )
		for address in self.address_to_user:
			if not name or name not in self.address_to_user[ address ]:
				print "Data sent to" + str( address )
				self.socket.sendto( pickled_data, address )

server = ServerGame()

server.start()