Esempio n. 1
0
class Client(object):
    def __init__(self):
        self.window = WindowLogin()
        self.room = WindowChat()
        self.room.withdraw()
        self.conn = ClientSocket()
        self.response_handle_functions = dict()
        self.is_running = True
        self.username = None
        self.register(RESPONSE_LOGIN_RESULT,
                      lambda data: self.resonse_login_handle(data))
        self.register(RESPONSE_CHAT,
                      lambda data: self.reponse_chat_handle(data))

    def startup(self):
        self.conn.connect_server()
        Thread(target=lambda: self.response_handle()).start()
        self.window.mainloop()

    def response_handle(self):
        while self.is_running:
            response_text = None
            try:
                response_text = self.conn.recv_data()
                print("response_text = {}".format(response_text))
            except BlockingIOError:
                sleep(0.1)
                continue
            response_data = self.parsing_response_text(response_text)
            handle_function = self.response_handle_functions[
                response_data["response_id"]]
            if handle_function:
                handle_function(response_data)

    @staticmethod
    def parsing_response_text(response_text):
        response_text_list = response_text.split(DELIMITER)
        response_data = dict()
        response_data["response_id"] = response_text_list[0]

        if response_text_list[0] == RESPONSE_LOGIN_RESULT:
            response_data["result"] = response_text_list[1]
            response_data["nickname"] = response_text_list[2]
            response_data["username"] = response_text_list[3]
        if response_text_list[0] == RESPONSE_CHAT:
            response_data["nickname"] = response_text_list[1]
            response_data["messages"] = response_text_list[2]
        return response_data

    def register(self, response_id, handle_function):
        self.response_handle_functions[response_id] = handle_function

    def response_login_handle(self, response_data):
        result = response_data["result"]
        print("result = {}".format(result))
        nickname = response_data["nickname"]
        if result == "0":
            showinfo("提示", "用户名或者密码错误")
            return
        self.username = response_data["username"]
        showinfo(("提示", "登陆成功"))

        #显示聊天窗口
        self.room.set_title(nickname)
        self.room.update()
        self.room.deiconify()

        #隐藏登录窗口
        self.window.withdraw()

    def response_chat_handle(self, response_data):
        nickname = response_data["nickname"]
        messages = response_data["messages"]

        self.room.append_message(nickname, messages)

        self.window.on_reset_button_click(lambda: self.clear_inputs())
        self.window.on_login_button_click(lambda: self.send_login_data())
        self.window.on_window_closed(lambda: exit())

        self.room.on_send_button_click(lambda: self.send_chat_data())
        self.room.on_window_closed(lambda: self.exit())

    def exit(self):
        self.is_running = False
        self.conn.close()
        sys.exit(0)

    def clear_inputs(self):
        self.window.clear_username()
        self.window.clear_password()

    def send_login_data(self):
        username = self.window.get_username()
        password = self.window.get_password()
        request_text = RequestProtocol.request_login(username, password)
        print('发送的聊天内容:', request_text)
        self.conn.send_data(request_text)

    def send_chat_data(self):
        chat_contents = self.room.get_input()
        self.room.clear_input()
        self.room.append_message("我", chat_contents)
        request_text = RequestProtocol.request_chat(self.username,
                                                    chat_contents)
        self.conn.send_data(request_text)
Esempio n. 2
0
class Client(object):
    """客户端"""
    def __init__(self):
        # 创建登录窗口
        self.window = WindowLogin()
        # 创建聊天室窗口并隐藏
        self.room = WindowChat()
        self.room.withdraw()
        # 服务器连接对象
        self.conn = ClientSocket()
        # 存储响应处理函数
        self.response_handle_functions = dict()
        # 处理服务器响应线程是否正在运行
        self.is_running = True
        # 当前登录用户, 未登录之前为None
        self.username = None

        # 登录窗口按钮绑定点击处理方法
        self.window.on_reset_button_click(lambda: self.clear_inputs())
        self.window.on_login_button_click(lambda: self.send_login_data())
        self.window.on_window_closed(lambda: self.exit())

        # 聊天室窗口发送按钮绑定处理函数
        self.room.on_send_button_click(lambda: self.send_chat_data())
        self.room.on_window_closed(lambda: self.exit())

        # 注册响应处理函数
        self.register(RESPONSE_LOGIN_RESULT,
                      lambda data: self.response_login_handle(data))
        self.register(RESPONSE_CHAT,
                      lambda data: self.response_chat_handle(data))

    def register(self, response_id, handle_function):
        """注册响应处理函数"""

        self.response_handle_functions[response_id] = handle_function

    def exit(self):
        """退出程序"""

        self.is_running = False
        self.conn.close()
        sys.exit(0)

    def clear_inputs(self):
        """清空输入框内容"""

        self.window.clear_username()
        self.window.clear_password()

    def send_login_data(self):
        """发送登录数据到服务器"""

        # 获得用户输入内容
        username = self.window.get_username()
        passowrd = self.window.get_password()
        # 构造登录请求
        request_text = RequestProtocol.request_login(username, passowrd)
        print('发送的聊天内容:', request_text)
        # 发送请求
        self.conn.send_data(request_text)

    def send_chat_data(self):
        """发送聊天数据到服务器"""

        # 获得聊天内容
        chat_contents = self.room.get_inputs()
        # 清空输入内容
        self.room.clear_inputs()
        # 显示聊天内容
        self.room.append_message("我", chat_contents)
        # 生成聊天协议内容
        request_text = RequestProtocol.request_chat(self.username,
                                                    chat_contents)
        # 向服务器端发送聊天数据
        self.conn.send_data(request_text)

    def startup(self):
        """启动客户端"""

        # 连接服务器
        self.conn.connect_server()
        # 创建线程处理服务器返回的响应
        Thread(target=lambda: self.response_handle()).start()
        # 窗口主循环
        self.window.mainloop()

    def response_handle(self):
        while self.is_running:

            response_text = None
            try:
                # 接受服务器端返回的数据
                response_text = self.conn.recv_data()
            except BlockingIOError:
                sleep(0.1)
                continue
            # 响应编号和响应内容
            response_data = self.parsing_response_text(response_text)
            # 获取对应处理函数
            handle_function = self.response_handle_functions[
                response_data['response_id']]

            if handle_function:
                handle_function(response_data)

    def response_login_handle(self, response_data):
        """登录响应处理"""

        result = response_data["result"]
        nickname = response_data["nickname"]
        if result == "0":
            showinfo("提示", "用户名或密码错误")
            return

        # 登录成功处理
        self.username = response_data["username"]
        showinfo("提示", "登陆成功!")
        # 显示聊天窗口
        self.room.set_title(nickname)
        self.room.update()
        self.room.deiconify()
        # 隐藏登录窗口
        self.window.withdraw()

    def response_chat_handle(self, response_data):
        """聊天响应处理"""

        nickname = response_data['nickname']
        messages = response_data['messages']
        # 显示聊天内容
        self.room.append_message(nickname, messages)

    @staticmethod
    def parsing_response_text(response_text):
        """解析服务器返回的字符串"""

        # 响应编号
        response_text_list = response_text.split(DELIMITER)
        # 保存解析后的数据
        response_data = dict()
        response_data["response_id"] = response_text_list[0]

        # 如果响应的是登录结果
        if response_text_list[0] == RESPONSE_LOGIN_RESULT:
            response_data["result"] = response_text_list[1]
            response_data["nickname"] = response_text_list[2]
            response_data["username"] = response_text_list[3]

        # 如果响应的是聊天内容
        if response_text_list[0] == RESPONSE_CHAT:
            response_data['nickname'] = response_text_list[1]
            response_data['messages'] = response_text_list[2]

        return response_data
Esempio n. 3
0
class Client(object):
    def __init__(self):
        #create login window:
        self.window = WindowLogin()
        self.window.on_reset_button_click(self.clear_inputs)
        self.window.on_login_button_click(self.send_login_data)
        #self.window.on_window_close(self.exit)
        #create chat window
        self.window_chat = WindowChat()
        #self.window_chat.on_window_close(self.exit)
        #hide the chat window
        self.window_chat.withdraw()
        #####create the client socket
        self.conn = ClientSocket()

        self.response_handle_function = {}
        self.response_handle_function[
            RESPONSE_LOGIN_RESULT] = self.response_login_handle
        self.response_handle_function[
            RESPONSE_CHAT] = self.response_chat_handle
        self.window_chat.on_send_button_click(self.send_chat_data)
        #define the global variable and record user name
        self.username = None
        #flag running program
        self.isrunning = True

    def startup(self):
        # Connect the client socket to the server
        self.conn.connect()
        # Since a message may be received at any time, the receiving message should be placed in the thread.
        # The difference between sever and server is that sever waits for the client response by starting up in a loop.
        # But each time the loop starts the child thread to see if there are any new user requests that need to be processed.
        # The client only starts up once (mainloop is an infinite loop).
        #Then we start the response_handle thread directly, enter the response_handle thread and loop through the child thread
        t = Thread(target=self.response_handle)
        t.start()
        # openning the login window is an endless loop, so finally open it
        self.window.mainloop()

    def clear_inputs(self):
        #clean up the window
        self.window.clear_username()
        self.window.clear_password()

    def send_login_data(self):
        #send the login message(login number and user name) to the server
        #get the typed in password
        username = self.window.get_username()
        password = self.window.get_password()
        # generate request text (encapsulation)
        request_text = RequestProtocol.request_login_result(username, password)
        #send request text to the server
        self.conn.send_data(request_text)

    def response_handle(self):
        #Continuously receive new messages from the processing server(while true +thread)
        #while self.isrunning:
        while True:
            recv_data = self.conn.recv_data()
            #parsing message (one dictionary)
            response_data = self.parse_response_data(recv_data)
            #handle according to the message
            handle_function = self.response_handle_function.get(
                response_data['response_id'])
            if handle_function:
                handle_function(response_data)

            #if response_data['response_id']==RESPONSE_LOGIN_RESULT:
            #self.response_login_handle(response_data)
            #elif response_data['response_id']==RESPONSE_CHAT:
            #self.response_chat_handle(response_data)

    #no used of self, removed self using static method
    @staticmethod
    def parse_response_data(recv_data):
        #There are two kinds of messages that need to be processed:
        # 1.Log in response from the server:1001|success|username|user id
        # or 1001|failure|null
        # 2.Chat server forwarding response:1002|sender's username|message
        response_data_list = recv_data.split(DELIMITER)
        ####
        response_data = {}
        response_data['response_id'] = response_data_list[0]

        if response_data['response_id'] == RESPONSE_LOGIN_RESULT:
            response_data['result'] = response_data_list[1]
            response_data['nickname'] = response_data_list[2]
            response_data['username'] = response_data_list[3]

        elif response_data['response_id'] == RESPONSE_CHAT:
            response_data['nickname'] = response_data_list[1]
            response_data['message'] = response_data_list[2]
        return response_data

    def response_login_handle(self, response_data):
        #login resulr
        print('Login result recieved')
        result = response_data['result']
        if result == '0':
            print('Login Failed')
            #The prompt box displays the title and content
            showinfo('Login result', 'Login Failed,wrong information!')
            return

        showinfo('Login result', 'Login Success!')
        nickname = response_data['nickname']
        self.username = response_data['username']
        print('%s has successfully login,nickname is %s' %
              (self.username, nickname))
        #Sets the title of the chat window
        self.window_chat.set_title(nickname)
        #Habitually refresh
        self.window_chat.update()
        #Display chat window, hide login window
        self.window_chat.deiconify()
        self.window.withdraw()

    def send_chat_data(self):
        #Gets the contents of the input box and sends it to the server
        #Get input
        message = self.window_chat.get_inputs()
        #clear up input box
        self.window_chat.clear_input()
        #Splicing message encapsulation
        request_text = RequestProtocol.request_chat(self.username, message)
        #send message
        self.conn.send_data(request_text)
        #Show the sending message to the chat area:
        self.window_chat.append_message('me', message)

    def response_chat_handle(self, response_data):
        #Get chat message respond from server
        sender = response_data['nickname']
        message = response_data['message']
        self.window_chat.append_message(sender, message)

    def exit(self):
        #exit the program
        self.is_running = False
        self.conn.close()
        sys.exit(0)
Esempio n. 4
0
class Client(object):
    def __init__(self):
        #create a window for login

        self.window = WindowLogin()
        self.window.on_reset_button_click(self.clear_inputs)
        self.window.on_login_button_click(self.send_login_data)
        #self.window.on_window_close(self.exit)

        #create window for chat
        self.window_chat = WindowChat()
        #self.window_chat.on_window_close(self.exit)

        #hide chat window
        self.window_chat.withdraw()

        ###create socket for client
        self.conn = ClientSocket()

        self.response_handle_function = {}
        self.response_handle_function[
            RESPONSE_LOGIN_RESULT] = self.response_login_handle
        self.response_handle_function[
            RESPONSE_CHAT] = self.response_chat_handle
        self.window_chat.on_send_button_click(self.send_chat_data)

        #define a global variable to recode username online
        self.username = None

        #Whether the program is running
        self.isrunning = True

    def startup(self):

        #connect client socket to the server

        self.conn.connect()

        #Client may receive message at anytime, so we put this process in a thread
        #in the server, we use a loop in start up function to wait for the response of client
        #every loop we create a sub thread to check whether there is new client request
        #In client we just need to start once, beacuse mainloop is an endless loop
        #Then we start response_handle, and loop in sub thread

        t = Thread(target=self.response_handle)
        t.start()

        #start login window is a endless loop, we put this at the last of the program
        self.window.mainloop()

    def clear_inputs(self):
        #clear window
        self.window.clear_username()
        self.window.clear_password()

    def send_login_data(self):

        #send request, username and password to server
        #get username and password input

        username = self.window.get_username()
        password = self.window.get_password()

        #create a protocol and wrappe it
        request_text = RequestProtocol.request_login_result(username, password)

        #send it to server
        self.conn.send_data(request_text)

    def response_handle(self):

        #continually accept data from server
        #while self.isrunning:
        while True:
            recv_data = self.conn.recv_data()

            #parse data(dictionary)
            response_data = self.parse_response_data(recv_data)

            #according to message processing,handle the data
            handle_function = self.response_handle_function.get(
                response_data['response_id'])
            if handle_function:
                handle_function(response_data)

            #if response_data['response_id']==RESPONSE_LOGIN_RESULT:
            #self.response_login_handle(response_data)
            #elif response_data['response_id']==RESPONSE_CHAT:
            #self.response_chat_handle(response_data)

    #self is not used in a static function
    @staticmethod
    def parse_response_data(recv_data):

        #There are two ways to handle messafe
        #1. server send a login request 1001|success|nickname|username or 1001|fail|
        #2. server send a chat request 1002|nickname|message

        response_data_list = recv_data.split(DELIMITER)
        ####
        response_data = {}
        response_data['response_id'] = response_data_list[0]

        if response_data['response_id'] == RESPONSE_LOGIN_RESULT:
            response_data['result'] = response_data_list[1]
            response_data['nickname'] = response_data_list[2]
            response_data['username'] = response_data_list[3]

        elif response_data['response_id'] == RESPONSE_CHAT:
            response_data['nickname'] = response_data_list[1]
            response_data['message'] = response_data_list[2]
        return response_data

    def response_login_handle(self, response_data):
        #response login
        print('Login result recieved')
        result = response_data['result']
        if result == '0':
            print('Login Failed')

            #print the title and content
            showinfo('Login result', 'Login Failed,wrong information!')
            return

        showinfo('Login result', 'Login Success!')
        nickname = response_data['nickname']
        self.username = response_data['username']
        print('%s has successfully login,nickname is %s' %
              (self.username, nickname))

        #set title of chat window
        self.window_chat.set_title(nickname)

        #refersh
        self.window_chat.update()

        #show the chat window and hide login window
        self.window_chat.deiconify()
        self.window.withdraw()

    def send_chat_data(self):
        #get message in the input box and send it to the server
        #get message
        message = self.window_chat.get_inputs()
        #clear the input box
        self.window_chat.clear_input()
        #join message together and wrappe it
        request_text = RequestProtocol.request_chat(self.username, message)
        #send the message
        self.conn.send_data(request_text)
        #show the message client send in chat window

        self.window_chat.append_message('me', message)

    def response_chat_handle(self, response_data):

        #receive the chat response by server
        sender = response_data['nickname']
        message = response_data['message']
        self.window_chat.append_message(sender, message)

    def exit(self):
        #exit program
        self.is_running = False
        self.conn.close()
        sys.exit(0)