Example #1
0
    def _listener(self):
        while True:
            data = network.receive(self._sock)

            if data is None:
                break

            log_event_receive(data['event'],
                              data['args'],
                              label='RemoteInterface')

            {
                'set_blocks': self._event_set_blocks,
                'set_chunks': self._event_set_chunks,
                'set_players': self._event_set_players,
                'remove_player': self._event_remove_player,
                'set_mobs': self._event_set_mobs,
                'set_items': self._event_set_items,
                'add_items': self._event_add_items,
                'remove_items': self._event_remove_items,
                'set_time': self._event_set_time,
                'logout': self._event_logout,
                'error': self._event_error
            }[data['event']](*data.get('args', []))

            if data['event'] == 'error':
                break
def game_list(session):
	while(1):
		network.send( session, packet.gamelist_request())
		time.sleep(1)
		a = network.receive( session )
		if a==None: continue

		if a["__type"] ==  "GameListReply:#Messages.ReplyMessages":
			return session, a["GameInfo"]
		else:
			log.warning("Unexpected packet received: " + str(a) )
			return session, None
def login(fname, lname, anumber, alias, endpoint, label=None):
	
	if label==None: label=alias
	
	id = packet.ID()

	id.fname = fname
	id.lname = lname
	id.alias = alias
	id.anumber = anumber
	
	session = Session()
	
	#only ipv4 for now. Splits port from IP
	(address, port) = endpoint.split(":")
	port = eval(port)
	
	session.registry = (address,port)
	
	session.id = id
	while session.socket == None:
		session.socket = network.create_socket()
	
	log.info("Logging in")
	
	#While we're still waiting on a login reply, keep listening
	status = 0
	while(session.login == False):
		network.send( session, packet.login_request(session.id, label) )
		time.sleep(1)
		data = network.receive(session)
		if data==None: continue

		if(data["__type"] == "LoginReply:#Messages.ReplyMessages"):
			if(data["Success"]):
				log.info("Login succeeded")
				session.procinfo = data["ProcessInfo"]
				session.login = True
			else:
				log.error("Login failed")
				log.error("Error message was: "+ data["Note"])
				return session
		else:
			log.warning("Unexpected packet received: " + str(data) )

	return session
Example #4
0
    def _listener(self):
        while True:
            data = network.receive(self._sock)

            if data is None:
                break

            log_event_receive(data['event'], data['args'], label='RemoteInterface')

            {'set_blocks': self._event_set_blocks,
             'set_chunks': self._event_set_chunks,
             'set_players': self._event_set_players,
             'remove_player': self._event_remove_player,
             'set_time': self._event_set_time,
             'logout': self._event_logout,
             'error': self._event_error
             }[data['event']](*data.get('args', []))

            if data['event'] == 'error':
                break
Example #5
0
def opTurn():
    ################################################################################
    # Opponents ##time to hit (waiting for opponent hit)
    # - either you will lose
    # - or opponent hit empty location or a ship location
    # - or opponent hit a mine
    # 	- You get additional info about a nearby location to the opponent's ship
    ################################################################################
    ansGot = network.receive()
    time.sleep(0.5)

    if ansGot == 'lost':  # All of my boat hit
        return True  #break

    elif ansGot == None:  # Either one of by boat or nothing is hit
        return 'pass'

    else:
        ansGot = list(map(int, ansGot.split(',')))  # Mine is hit
        print(ansGot[0], ansGot[1], "is nearby location of the ship")
        return ansGot
Example #6
0
    def joinNetwork(self, bootstrapIP):

        # Create a Join Message and send it to the bootstrap peer
        joinMsg = {
            TYPE: JOIN,
            SEND_IP: MY_IP,
            DEST_IP: bootstrapIP,
        }

        # Wait for the JOIN_ACK message
        while not self.isJoined:

            # If error sending JOIN message
            while not network.send(bootstrapIP, **joinMsg):
                time.sleep(ERROR_RETRY)
                logger.warning(
                    'Failed to send JOIN message to {}'.format(bootstrapIP))
            logger.info('Sent JOIN message to {}'.format(bootstrapIP))

            clientsock, address = self.sock.accept()

            if address[0] == bootstrapIP:

                data = network.receive(clientsock)
                if data and data[TYPE] == JOIN_ACK:

                    self.GUID = data[DEST_GUID]
                    self.isJoined = True

                    # Initialise RT
                    self.routTab.initialise(rt=data[ROUTING],
                                            myGUID=self.GUID,
                                            Central_GUID=data[SEND_GUID],
                                            Central_IP=bootstrapIP)

                    # State Details
                    print("Joined Network! Your GUID: {}".format(self.GUID))
                    logger.info('Joined Network! GUID: {}'.format(self.GUID))
def join_game(session, game):
	
	session.gamemgr = game["GameManager"]
	
	while session.gamelogin == False:
		#Keep trying to join game until it works
		network.send_game(session, packet.joingame_request(game))
		time.sleep(1)
		data = network.receive(session)
		if data==None: continue

		if(data["__type"] == "JoinGameReply:#Messages.ReplyMessages"):
			if(data["Success"]):
				log.info("Login succeeded")
				session.gamelogin = True
			else:
				log.error("Login failed")
				log.error("Error message was: "+ data["Note"])
				return session
		else:
			log.warning("Unexpected packet received: " + str(data) )

	return session
session = client.login(
	args.fname,
	args.lname,
	args.anumber,
	args.alias,
	args.endpoint
)


while(session.gamemgr == None):
	log.info("Requesting Game List")

	#get the game list
	session, games = client.game_list(session)

	if(games != None):
		log.info("Game List Received")
		log.debug(str(games))
		
		#try joining some games
		for game in games:
			log.info("Joining game: "+game["Label"])
			session = client.join_game(session,game)
			if session.gamemgr != None: break

log.info("Successfully joined game.")

#Nothing left to do - in a game. Just check for keepalive packets
while(1):
	network.receive(session)
haha = 0
rekt = 0
rHint = ''
cHint = ''
rHit = -1
cHit = -2
rFinal = -8
cFinal = -7
rEnd = -20
cEnd = -19
rWater = -50
cWater = -49

while True:

    ans = network.receive()

    if rekt == 0:
        for m in range(10):
            for n in range(10):
                if dispBoard[m][n] == ' ':
                    rWater = m
                    cWater = n
                    rekt += 1

    if cnt == 0:
        for k in range(10):
            for l in range(10):
                if dispBoard[k][l] == 'x':
                    rHit = k
                    cHit = l
Example #10
0
    def msgHandler(self, clientsock, address):

        msg = network.receive(clientsock)

        if not msg:
            logger.warning('Did not receive message properly from {}'.format(
                address[0]))
            return

        if (DEST_GUID in msg and msg[DEST_GUID] != self.GUID):
            logger.warning(
                'Not the intended recipient for message. From {}. Destination GUID: {}'
                .format(msg[SEND_IP], msg[DEST_GUID]))
            return

        # If received Join message (for bootstrap node)
        if msg[TYPE] == JOIN:
            if self.isBootstrap:
                logger.info('Received JOIN message from {}'.format(
                    msg[SEND_IP]))
                joinAck = {
                    TYPE: JOIN_ACK,
                    SEND_IP: MY_IP,
                    SEND_GUID: self.GUID,
                    DEST_IP: msg[SEND_IP],
                    DEST_GUID: network.generate_guid(),
                    ROUTING: self.routTab.getTable()
                }
                network.send(joinAck[DEST_IP], **joinAck)
                self.routTab.addPeer(GUID=joinAck[DEST_GUID],
                                     IPAddr=joinAck[DEST_IP])
                logger.info('Assigned GUID {} to {}'.format(
                    joinAck[DEST_GUID], joinAck[DEST_IP]))
            else:
                logger.warning('Join message received! But not bootstrap node')

        # Reciving PING message
        if msg[TYPE] == PING:
            logger.info('Received PING message from {} ({})'.format(
                msg[SEND_IP], msg[SEND_GUID]))
            pongMsg = {
                TYPE: PONG,
                SEND_IP: MY_IP,
                SEND_GUID: self.GUID,
                DEST_IP: msg[SEND_IP],
                DEST_GUID: msg[SEND_GUID]
            }
            network.send(msg[SEND_IP], **pongMsg)
            self.routTab.handlePing(msg)

        # Receiving PONG message
        elif msg[TYPE] == PONG:
            logger.info('Received PONG message from {} ({})'.format(
                msg[SEND_IP], msg[SEND_GUID]))
            self.routTab.handlePong(msg)

        # Receiving QUERY message
        elif msg[TYPE] == QUERY:
            logger.info(
                'Received QUERY message with ID {} from {} ({}). Source:- {} ({})'
                .format(msg[QUERY_ID], msg[SEND_IP], msg[SEND_GUID],
                        msg[SOURCE_IP], msg[SOURCE_GUID]))

            # Check whether the query is repeated
            with self.repQuerLock:
                ok = msg[QUERY_ID] in self.repQuer

            # If not repeated search database and forward query
            if not ok:

                # Throw away older cached query and add the query to the cache
                with self.repQuerLock:
                    while self.repQuerQueue.qsize() >= REP_QUERY_CACHE:
                        self.repQuer.discard(self.repQuerQueue.get())
                    self.repQuer.add(msg[QUERY_ID])
                    self.repQuerQueue.put(msg[QUERY_ID])
                    self.save_repQuerQueue(msg[QUERY_ID])
                logger.info('Adding Query {} to cache'.format(msg[QUERY_ID]))

                sender = msg[SEND_GUID]
                msg[SEND_IP] = MY_IP
                msg[SEND_GUID] = self.GUID

                # Search for results in database and send back if any
                results = self.fileSys.search(msg[SEARCH])
                if bool(results):
                    reponseMsg = {
                        TYPE: QUERY_RESP,
                        SEND_IP: MY_IP,
                        SEND_GUID: self.GUID,
                        DEST_IP: msg[SOURCE_IP],
                        DEST_GUID: msg[SOURCE_GUID],
                        QUERY_ID: msg[QUERY_ID],
                        RESULTS: results
                    }
                    network.send(msg[SOURCE_IP], **reponseMsg)
                    logger.info(
                        'Sending {} response(s) to Query {} to {} ({})'.format(
                            len(results), msg[QUERY_ID], msg[SOURCE_IP],
                            msg[SOURCE_GUID]))

                # Send queries to neighbours in Table
                for neighbours in self.routTab.neighbours():
                    msg[DEST_IP] = neighbours[0]
                    msg[DEST_GUID] = neighbours[1]
                    if msg[DEST_GUID] != sender:
                        network.send(msg[DEST_IP], **msg)
                        logger.info(
                            'Forwarding query to neighbour {} ({})'.format(
                                msg[DEST_IP], msg[DEST_GUID]))

            else:
                logger.info('Repeated query {}'.format(msg[QUERY_ID]))

        # If received QUERY_RESP message
        elif msg[TYPE] == QUERY_RESP:
            logger.info(
                'Received QUERY_RESP with {} result(s) for query {} from {} ({})'
                .format(
                    len(msg[RESULTS]),
                    msg[QUERY_ID],
                    msg[SEND_IP],
                    msg[SEND_GUID],
                ))
            with self.queryResLock:
                if msg[QUERY_ID] in self.queryRes:
                    self.queryRes[msg[QUERY_ID]].append(msg)
                    self.save_queryRes()  # Save State
                    return
            logger.warning('Query {} previously discarded'.format(
                msg[QUERY_ID]))

        # If received TRANSFER_REQ
        elif msg[TYPE] == TRANSFER_REQ:
            logger.info(
                'Received TRANSFER_REQ from {} ({}) for File ID {} and Chunk {}'
                .format(msg[SEND_IP], msg[SEND_GUID], msg[FILE_ID],
                        msg[CHUNK_NO]))
            fileTranMsg = {
                TYPE: TRANSFER_FILE,
                SEND_IP: MY_IP,
                SEND_GUID: self.GUID,
                DEST_IP: msg[SEND_IP],
                DEST_GUID: msg[SEND_GUID],
                REQUEST_ID: msg[REQUEST_ID],
                CHUNK_NO: msg[CHUNK_NO],
                CONTENT: self.fileSys.getContent(msg[FILE_ID], msg[CHUNK_NO])
            }
            if fileTranMsg[CONTENT] is None:
                logger.warning('Content Unavailable for File ID {}'.format(
                    msg[FILE_ID]))
            else:
                network.send(msg[SEND_IP], **fileTranMsg)

        # If received TRANSFER_FILE message
        elif msg[TYPE] == TRANSFER_FILE:
            logger.info(
                'Received TRANSFER_FILE from {} ({}) for Request ID {} and Chunk {}'
                .format(msg[SEND_IP], msg[SEND_GUID], msg[REQUEST_ID],
                        msg[CHUNK_NO]))
            with self.chunkLeftLock:
                # If the request is not yet done and the write to the file system is successful
                if msg[CHUNK_NO] in self.chunkLeft.get(msg[REQUEST_ID], (0, set()))[1] \
                        and self.fileSys.writeChunk(msg):

                    # Remove the chunk no from the required chunk list
                    self.chunkLeft[msg[REQUEST_ID]][1].remove(msg[CHUNK_NO])

                    # If all the chunks are done, inform filesys of the completion
                    if not bool(self.chunkLeft[msg[REQUEST_ID]][1]):
                        self.fileSys.done(msg[REQUEST_ID])
                        del self.chunkLeft[msg[REQUEST_ID]]
                        del self.chunkLeftTransferReq[msg[REQUEST_ID]]
                        self.save_pending()  # Force Save State

                    else:
                        self.save_pending(False)  # Save State