示例#1
0
def listener(msgList: tkinter.Text, s: socket,
             clientEncryptor: PKCS1OAEP_Cipher):
    while True:
        if s.fileno() == -1:
            # socket closed
            break
        r, _, _ = select.select([s], [], [])
        for rs in r:
            if s == rs:
                try:
                    data = rs.recv(4096)
                except OSError:
                    # connection terminated (for some reason)
                    break
                if not data:
                    break
                msg = clientEncryptor.decrypt(data)
                msg = pickle.loads(msg)
                if msg[0]:
                    message = "<SERVER>: " + msg[3]
                else:
                    message = msg[2] + ": " + msg[3]
                msgList.tag_config(str(msg[1]), foreground=str(msg[1]))
                msgList.config(state=tkinter.NORMAL)
                msgList.insert(tkinter.END, message + '\n', str(msg[1]))
                msgList.config(state=tkinter.DISABLED)
示例#2
0
def client_mgr(cli, serverEncryptor: PKCS1OAEP_Cipher):
    while True:
        try:
            message = cli.conn.recv(4096)
        except (ConnectionResetError, ConnectionAbortedError):
            # Connection failed, possibly due to a non-expected termination on client side
            # i.e. client crashed or force close
            try:
                active_connections.remove(cli)
                cli.conn.shutdown(socket.SHUT_RDWR)
                cli.conn.close()
                msg_handler(User(None, None, "<SERVER>", None, "#FF0000"),
                            cli.nick + serverAlertMessages["USERDISCONNECT"])
            except ValueError:
                pass
            break
        if message:
            # handle client message here
            # decrypt message object
            message = serverEncryptor.decrypt(message)
            message = pickle.loads(message)
            print(cli.nick, ":", message[1])
            if message[0]:
                # if message[0] is true for messages sent to the server, that message is a control message
                # think /quit, /nick, etc.
                if not control_msg_handler(cli, message[1]):
                    # control_msg_handler returns False, so we are terminating connection
                    break
            # if non-control message, broadcast message
            else:
                msg_handler(cli, message[1])
        else:
            # message is empty. Do we kill the connection, or do we send an error message?
            # prevent empty message sent from client side?
            # remove client from the list of connected clients
            pass