示例#1
0
    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))
示例#2
0
    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
示例#3
0
    def authenticate(self):
        
        try:
            hashes = self.__generateParcialHashes()
            sock = ClientSocket(self.address,self.abi,hashes)
            
        except IOError as e:
            print(e.message)
            return -1  

        
        return sock.authenticate()
示例#4
0
 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))
示例#5
0
class Main:

    host = "192.168.0.11"
    port = 8081
    observer = ''
    client = ''

    def __init__(self):
        self.client = ClientSocket(self.host, self.port)
        self.client.make_configuration()
        self.client.make_connection()
        self.observer = FSHandler(self.client.client_socket, self.host,
                                  self.port)

    def process(self):
        threading.Thread(target=self.observer.start_observer).start()
        threading.Thread(target=self.client.listen_to_server).start()
示例#6
0
class Main:

    host = os.getenv("HOST")
    port = int(os.getenv("PORT"))
    observer = ''
    client = ''

    def __init__(self):
        self.client = ClientSocket(self.host, self.port)
        self.port, addr = self.client.make_configuration()
        self.client.make_connection()
        self.observer = FSHandler(self.client.client_socket, self.host,
                                  self.port, addr)

    def process(self):
        threading.Thread(target=self.observer.start_observer).start()
        threading.Thread(target=self.client.listen_to_server).start()
示例#7
0
 def add_state_socket(self, ws):
     sock = ClientSocket(ws)
     data = sock.receive()
     if data:
         data = self.command.parse(data)
     if data and data.type == self.command_id.register:
         sock.set_id(data.id)
         self.sockets.append(sock)
     else:
         sock.close()
示例#8
0
def test_marketdata(production):
    """client account information -> setup GDAX connection and print data"""
    p_ids = ['BTC-USD']
    client_socket = ClientSocket(products=p_ids,
                                 auth=True,
                                 api_key=production['api_key'],
                                 api_secret=production['api_secret'],
                                 api_passphrase=production['api_pass'],
                                 channels=[
                                     "level2", "heartbeat", {
                                         "name": "ticker",
                                         "product_ids": p_ids
                                     }
                                 ])
    client_socket.start()
    print(client_socket.url, client_socket.products)

    try:
        while True:
            print("\nMessageCount =", "%i \n" % client_socket.msg_count)
            time.sleep(1)
    except KeyboardInterrupt:
        client_socket.close()

    if client_socket.error:
        sys.exit(1)
    else:
        sys.exit(0)
示例#9
0
    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
class SendingQueue():
    ''' Class to sending queue process '''
    def __init__(self, server_address):
        ''' Create SendingQueue object '''
        self.threads = []
        # gevent provides a synchronized queue (locking is handled)
        self.queue = queue.Queue()
        self.socket_mgr = ClientSocket(server_address)

    def add(self, segments):
        ''' A list of segments to the sending queue'''
        for sgmt in segments:
            self.queue.put(sgmt)

    def send(self):
        ''' Iterate continuously looking to send entries in queue
        '''
        logger.debug("Started sending thread")
        while True:
            if self.queue.qsize():
                self.socket_mgr.send(self.queue.get())
                time.sleep(1)  # send is non-blocking, don't over send
            else:
                time.sleep(3)

    def start_sending(self, filename, port_list, segments, num_threads):
        ''' Start a separate thread to begin sending
            from the send queue. Should be started before
            breaking up files. As segments are added to
            queue, it will send, until stop_sending is called.
        '''
        self.add(segments)
        self.socket_mgr.connect(filename, port_list)
        for i in range(num_threads):
            self.threads.append(gevent.spawn(self.send))
        return

    def complete_sending(self):
        ''' Join all threads created during this send process.
            This should be done between searching for new files
        '''
        # Wait till rest of send queue is empty
        # ASSUME no more is being added at this point
        logger.debug("Waiting for all segments to send before completing send")
        while self.queue.qsize():
            time.sleep(3)
        # Wait till sending finished
        while self.socket_mgr.num_currently_sending:
            logger.debug("Waiting for (%d) segments to finish sending",
                         self.socket_mgr.num_currently_sending)
            time.sleep(3)
        # Kill any threads created
        gevent.killall(self.threads, timeout=5)
        self.threads = []
        self.socket_mgr.disconnect()
示例#11
0
 def add_request_socket(self, ws):
     sock = ClientSocket(ws)
     while not sock.is_closed():
         data = sock.receive()
         if not data:
             sock.close()
             return
         data = self.command.parse(data)
         # Register
         if data and data.type == self.command_id.register and sock.get_id(
         ) is None:
             client_id = self.get_new_client_id()
             sock.set_id(client_id)
             if client_id:
                 sock.send(
                     self.command.build(
                         dict(type=self.command_id.register, id=client_id)),
                     True)
             else:
                 sock.send(
                     self.command.build(dict(type=self.command_id.error)),
                     True)
         # Position Update
         elif data.type == self.command_id.update:
             self.update_player_position(sock.client_id, data.x, data.y)
示例#12
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)
示例#13
0
                    print("ERROR: {}".format(sentence["error"]))
                    print("Say something: ")
                    sentence = voice.listen_sentence_from_mic(voice.recognizer, voice.microphone)

                # Print sentence
                print("Your command was: {}".format(sentence["transcription"]))

                # Sending command via socket
                clientsocket.send_command(sentence["transcription"].encode())
        except (KeyboardInterrupt, SystemExit):
            print("\n\nYou've finished this program. Thanks for using it. ;)")
            break


if __name__ == "__main__":
    host = "192.168.0.24"
    port = 6002

    # Creates an instance of the class that handles sockets
    client_socket = ClientSocket(host, port)

    # Creating thread to send instructions to the server
    voice_command_thread = threading.Thread(target=voice_command, args=(client_socket,))

    # Creating thread to check the status sent by the server
    checking_thread = threading.Thread(target=client_socket.check_status)

    # Starting all threads
    voice_command_thread.start()
    checking_thread.start()
示例#14
0
 def add_client(self, addr, socket):
     new_client = ClientSocket(addr, socket, ENCODING, HEADERSIZE)
     self.client_sockets.append(new_client)
     self.server_broadcast(f"SERVER: {new_client.addr} has entered chat")
     print(f"[NEW CONNECTION] {new_client.addr} connected")
示例#15
0
clients = []
measurments = []
maxElements = 6

RELAY_COMM = True

input_queue = multiprocessing.Queue()
output_queue = multiprocessing.Queue()

# IP_ADDR = '192.168.88.21'
IP_ADDR = '192.168.1.10'

video_cap = capture.SocketCapture(IP_ADDR)
# video_cap = capture.FileCapture('py_opencv\\traseu1.mp4')
comm_socket = ClientSocket(IP_ADDR, '8081')


class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')


class StaticFileHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('main.js')


class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print 'new connection'
示例#16
0
 def __init__(self):
     self.client = ClientSocket(self.host, self.port)
     self.port, addr = self.client.make_configuration()
     self.client.make_connection()
     self.observer = FSHandler(self.client.client_socket, self.host,
                               self.port, addr)
示例#17
0
eName = PATH + "errorlog.txt"  #the errorlog file
try:
    fName = glob.glob(PATH + "*_data.csv")[0]
    print("Got " + fName)  #print path to file
    print(fName[len(PATH):])  #print #file name

except IndexError:  #no file found
    print("Error")
    with open(eName, 'a') as f:
        print("Error no File Found for Upload: Exiting. Time: %i" %
              time.time(),
              file=f)
        f.close()
    exit(-1)  #error

con = ClientSocket()  #start client socket

with open(fName, 'r') as f:  #open up the file in read mode

    data = f.read()
    con.sendName(fName[len(PATH):]
                 )  #lets the server know which file is to be appended to
    con.send(data)  #send the file
    f.close()  #close the file

if (con.rec() == '200'):  #All clear condition
    print("Data Uploaded and received correctly")
    os.remove(fName)  #remove the file from the client
else:
    with open(eName, 'a') as f:
        print("Error Uploading: Keeping Data. Time: %i" % time.time(),
示例#18
0
clients = []
measurments = []
maxElements = 6

RELAY_COMM = True

input_queue = multiprocessing.Queue()
output_queue = multiprocessing.Queue()

# IP_ADDR = '192.168.88.21'
IP_ADDR = '192.168.1.10'

video_cap = capture.SocketCapture(IP_ADDR)
# video_cap = capture.FileCapture('py_opencv\\traseu1.mp4')
comm_socket = ClientSocket(IP_ADDR, '8081')


class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')


class StaticFileHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('main.js')


class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print 'new connection'
示例#19
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)
示例#20
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)
示例#21
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
 def __init__(self, server_address):
     ''' Create SendingQueue object '''
     self.threads = []
     # gevent provides a synchronized queue (locking is handled)
     self.queue = queue.Queue()
     self.socket_mgr = ClientSocket(server_address)
示例#23
0
def test_callback_func(msg):
    global done
    print("Rec'd: " + msg)
    if msg.find('quit') >= 0:
        print("Setting done == True")
        done = True

if __name__ == '__main__':
    global done
    parser = argparse.ArgumentParser(description='Client Socket class - Tester')
    parser.add_argument("port", type=int, help='Port on localhost to use')
    args = parser.parse_args()

    port = args.port if args.port else 12888

    c = ClientSocket('test', ('127.0.0.1', port), '')
    c.setCallback(test_callback_func)
    c.start()
    time.sleep(0.5)  # sleep a bit to allow reply

    start_ts = time.time()
    cnt = 0
    total_loops = 1000
    while not done:
        cnt = cnt+1 if cnt < total_loops else 1
        loop_update = {
            'LocX_mm': '%3.3f' % (randint(0, 500)+random()),
            'LocY_mm': '%3.3f' % (randint(0, 50)+random()),
            'Loop Count': str(cnt),
            'Run Mode': 'Recipe',
            'StageMoving': True,