Пример #1
0
def sendMove(r, c):
    global connection
    if connection is None:
        print("Fehler: Senden des Zuges nicht möglich. Es besteht keine Verbindung!")
    else:
        message = str(r)+'#'+str(c)
        connection.send(message)
Пример #2
0
def main():
    args = get_args()
    connector = get_connector()
    connection, success = connector.connect_waiting(args.host, args.port)
    if success:
        connector.send(connection, args.filename)
        connector.shutdown()
    else:
        print 'could not connect to host=%s, port=%d' % (args.host, args.port)
Пример #3
0
def main():
    args = get_args()
    connector = get_connector()
    connection, success = connector.connect_waiting(args.host, args.port)
    if success:
        connector.send(connection, args.filename)
        connector.shutdown()
    else:
        print "could not connect to host=%s, port=%d" % (args.host, args.port)
Пример #4
0
 def connectClient():
     ip = txt_IP.get()
     global connection
     if (connection.startClient(ip, port)):
         message = "Someone there?"
         connection.send(message)
         print("Client: Sent message: "+message)
         print("Client: Received message: "+str(connection.receive()))
         gamesize = int(connection.receive())
         showMap(gamesize, mode.CLIENT)
     else:
         print("Connection failed.")
Пример #5
0
 def send(self, data):
     """Stops the retriving, so we won't get OSError, and waits a little, so it has time to stop retriving, then sends the message.
     After a little wait, it restarts the retriving process...
     """
     msg = message(False, HEADERSIZE)
     msg.message = data
     msg.sender = username
     self.msg_ret.terminate()
     time.sleep(0.001)
     connector.send(client_socket, msg)
     time.sleep(0.001)
     self.msg_ret.start()
Пример #6
0
def send_welcome_message(client_socket):
    """Sends all saved messages, if the save_message flag is set. The messages are saved in a pickle.
    """
    if store_msgs:
        log("Sending message file...")
        msg = message(True, HEADERSIZE)
        msg.sender = NAME
        msg.set_file(f"{NAME}.msg")
        connector.send(client_socket, msg)
    else:
        msg = message(False, HEADERSIZE)
        msg.sender = NAME
        msg.message = "None"
Пример #7
0
    def connectServer():
        global connection
        if (connection.startServer(port)):
            message = str(connection.receive())
            if message:
                print("Server: Received message: "+message)
                message = "Acknowledged!"
                connection.send(message)
                print("Server: Sent message: " + message)
                gamesize = txt_gamesize.get()
                connection.send(str(gamesize))

                showMap(gamesize, mode.SERVER)
            print("Connection failed.")
Пример #8
0
def init_socket():
    """initializes the connection with the remote server on the given port.
    !IMPORTANT!
    The server's certification.pem file must be in the folder certif, with the server's IP address.
    """
    global client_socket
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect((IP, PORT))
    client_socket.setblocking(True)

    context = ssl.create_default_context(cafile='certif/Certification.pem') #FOR NOW? IT HAS TO BE NAMED CERTIFICATION!
    client_socket = context.wrap_socket(client_socket, server_hostname='furryresidency')
    #client_socket.setblocking(False)

    user_name = message(HEADERSIZE=HEADERSIZE)
    user_name.sender = username
    user_name.message = username
    if not connector.send(client_socket, user_name):
        print("Error in the connection!")
        exit(2)
    messages = connector.retrive(client_socket, HEADERSIZE, username)
    if not messages:
        print("Error in the connection!")
        exit(2)
    elif messages._has_file:
        messages.create_file(f"{username}.msg")
        tmp = []
        with open(f"{username}.msg", 'rb') as f:
            msgs = f.read(-1).split(b"\t\t||\n")
        for msg in msgs:
            if msg != b"":
                tmp.append(pickle.loads(msg))
        os.remove(f"{username}.msg")
        global init_msg
        init_msg = tmp
Пример #9
0
  def test_disconnect_finish_queue(self):
    converter = _PausingConverter()
    connector = self._get_connector(listening=True, converter=converter)
    connector.run()

    # Listen for the connector.
    listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listener.bind(('', TestConnector._LISTEN_PORT))
    listener.listen(1)

    # The connector should create a half-open connection to the listening socket.
    connection, success = connector.connect_waiting(
        '', TestConnector._LISTEN_PORT)
    self.assertTrue(success)
    # Accept the connection so now a full connection.
    s, addr = listener.accept()

    # Wait for the first message to be partially serialized.
    connector.send(connection, 'ONE')
    converter._wait_for_callback()
    # Enqueue the second message and disconnect.
    connector.send(connection, 'TWO')
    connector.disconnect(connection, now=True)
    # Continue serializing the first message.
    converter._use_callback()

    # Serialize the second message.
    converter._wait_for_callback()
    converter._use_callback()

    # Both messages are sent completely.
    msg = self.recv()
    self.assertEqual(msg.type(), connector.Event.FINISH_DISCONNECT)
    self.assertIsNone(msg.incomplete())
    self.assertFalse(msg.queued())

    # Both messages are received completely.
    all_recv_bytes = self._read_until_closed(s)
    self.assertEqual(all_recv_bytes, 'abcONE123abcTWO123')

    connector.shutdown()
Пример #10
0
    def test_disconnect_finish_queue(self):
        converter = _PausingConverter()
        connector = self._get_connector(listening=True, converter=converter)
        connector.run()

        # Listen for the connector.
        listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        listener.bind(('', TestConnector._LISTEN_PORT))
        listener.listen(1)

        # The connector should create a half-open connection to the listening socket.
        connection, success = connector.connect_waiting(
            '', TestConnector._LISTEN_PORT)
        self.assertTrue(success)
        # Accept the connection so now a full connection.
        s, addr = listener.accept()

        # Wait for the first message to be partially serialized.
        connector.send(connection, 'ONE')
        converter._wait_for_callback()
        # Enqueue the second message and disconnect.
        connector.send(connection, 'TWO')
        connector.disconnect(connection, now=True)
        # Continue serializing the first message.
        converter._use_callback()

        # Serialize the second message.
        converter._wait_for_callback()
        converter._use_callback()

        # Both messages are sent completely.
        msg = self.recv()
        self.assertEqual(msg.type(), connector.Event.FINISH_DISCONNECT)
        self.assertIsNone(msg.incomplete())
        self.assertFalse(msg.queued())

        # Both messages are received completely.
        all_recv_bytes = self._read_until_closed(s)
        self.assertEqual(all_recv_bytes, 'abcONE123abcTWO123')

        connector.shutdown()
Пример #11
0
def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    #Binding to the socket
    server_socket.bind((IP, PORT))
    #Starting to listen on port
    server_socket.listen()

    if store_msgs and not os.path.exists(f"{NAME}.msg"):
        msg = message(HEADERSIZE=HEADERSIZE)
        msg.sender = NAME
        msg.message = "Server created"
        with open(f"{NAME}.msg", 'wb') as f:
            f.write(pickle.dumps(msg) + b"\t\t||\n")

    context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    context.load_cert_chain('certif/Certification.pem', 'certif/Key.pem')
    server_socket = context.wrap_socket(server_socket, server_side=True)

    socket_list = [server_socket]
    clients = {}
    EXIT = False
    try:
        while True:
            read_socket, _, exception_socket = select.select(
                socket_list, [], socket_list)

            for notified_socket in read_socket:
                if notified_socket == server_socket:
                    client_socket, client_address = server_socket.accept()
                    log(f'Incoming connection from {client_address[0]} on {client_address[1]}'
                        )
                    try:
                        log("Retriving validator message...")
                        user = connector.retrive(client_socket, HEADERSIZE,
                                                 NAME)
                        log('Validation message retrived....')
                    except Exception as ex:
                        out.log(f"Exception while retriving message: {ex}")
                        log(f"Exception while retriving message: {ex}")
                        user = False

                    if user is False:
                        log('Return value was false!')
                        continue
                    log('Adding client to client list...')
                    socket_list.append(client_socket)
                    clients[client_socket] = user.message
                    log('Generating notification message...')
                    msg = message(HEADERSIZE=HEADERSIZE)
                    msg.sender = NAME
                    msg.message = f"{user.message} connected to the server!"
                    log(f'Sending welcome message...\nStore messages: {store_msgs}'
                        )
                    send_welcome_message(client_socket)
                    if store_msgs:
                        log('Saving notification....')
                        with open(f"{NAME}.msg", 'ab') as f:
                            f.write(pickle.dumps(msg) + b"\t\t||\n")
                    log(f"{user.message} connected to the server!")

                    log('Sending notification message...')
                    for client_socket in clients:
                        connector.send(client_socket, msg)
                    out.log(
                        f"Accepted new connection from {client_address[0]}:{client_address[1]} username:{user.message}"
                    )
                    log(f"Accepted new connection from {client_address[0]}:{client_address[1]} username:{user.message}"
                        )

                else:
                    try:
                        log(f'Incoming message from {clients[notified_socket]}'
                            )
                        msg = connector.retrive(notified_socket, HEADERSIZE,
                                                NAME)
                    except:
                        out.log(
                            f"Closed connection from {clients[notified_socket]}"
                        )
                        log(f"Closed connection from {clients[notified_socket]}"
                            )
                        socket_list.remove(notified_socket)
                        del clients[notified_socket]
                        continue
                    if "roll" in msg.message:
                        value = roller.roller(msg.message.replace("roll ", ''))
                        response = f"is rolled the followings: {value['rolled_values']}"
                        response += (
                            f", with the modifyer {value['modifier_applied']}"
                            if value["modifier_applied"] != None else "")
                        response += f". The total is {value['total']}."
                        msg.message = response

                    out.log(f"Retrived message from {msg.sender}")
                    log(f"Retrived message from {msg.sender}")
                    if store_msgs:
                        with open(f"{NAME}.msg", 'rb') as f:
                            data = f.read(-1).split(b"\t\t||\n")
                        if len(data) > 40:
                            del data[0]
                        data.append(pickle.dumps(msg))
                        with open(f"{NAME}.msg", 'wb') as f:
                            for m in data:
                                f.write(m + b"\t\t||\n")
                    for client_socket in clients:
                        connector.send(client_socket, msg)

            for notified_socket in exception_socket:
                socket_list.remove(notified_socket)
                del clients[notified_socket]
    except KeyboardInterrupt:
        EXIT = True
        out.log("User Interrupt")
    except Exception as e:
        out.log(e, error=True)
        log(e)
    finally:
        out.close()
        for s in socket_list:
            s.close()
        #socket_list[0].shutdown(socket.SHUT_RDWR)
        if EXIT:
            exit(0)