def setUp(self): self.server = socket(AF_INET, SOCK_STREAM) address = ('',1234) self.server.bind(address) self.server.listen() self.client = ChatClient("Mauricio","localhost",1234) self.client.init_socket()
def identify_client(self, client_socket, client_address): not_identified = True while not_identified: sleep(0.3) identify = "Ingresa 'IDENTIFY username' (donde username es el nombre que usarás)" client_socket.send(bytes(identify, "utf-8")) sleep(0.3) disconnect = "O bien, ingresa 'DISCONNECT' para salir" client_socket.send(bytes(disconnect, "utf-8")) message = client_socket.recv(self.bufsize).decode("utf-8") if message.startswith("IDENTIFY"): name = message[len("IDENTIFY "):] try: self.public_room.verify_name(name) except ExistingUsernameException: username_error = '"%s" ya está en uso. Prueba con otro\n' % name client_socket.send(bytes(username_error, "utf-8")) continue host, port = client_address client = ChatClient(name, host, port) client.set_server_socket(client_socket) print('{}:{} se ha identificado como: {}'.format( host, port, name)) greeting = '¡Hola %s! Ahora puedes comenzar a disfrutar de PyChat :)' % name client_socket.send(bytes(greeting, "utf-8")) join_message = "%s se ha unido al chat. ¡Sé amable y di hola!" % name self.public_room.broadcast(join_message) self.public_room.add_client(client) return True, client elif message == "DISCONNECT": goodbye = 'Hasta luego :)' client_socket.send(bytes(goodbye, "utf-8")) sleep(0.3) client_socket.close() print( "Un cliente no identificado con la direccion %s:%s se ha ido" % client_address) return False, None error = "¡Creo que has cometido un error!" client_socket.send(bytes(error, "utf-8"))
def runclient(): logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') parse = argparse.ArgumentParser("Client Options") parse.add_argument("-a", "--addr", default=settings.ADDR, type=str, help="set connect address") parse.add_argument("-p", "--port", default=settings.PORT, type=int, help="set connect port") args = parse.parse_args() addr = args.addr port = args.port loop = EventLoop() chat_client = ChatClient(addr, port) chat_client.add_to_loop(loop) try: loop.run() except (KeyboardInterrupt, IOError, OSError) as e: logging.error(e) import traceback traceback.print_exc()
def __init__(self, *args, **kwargs): super(RootBox, self).__init__(*args, **kwargs) self.chat_client = None self.receive_queue = Queue() # create the confirm box for quitting self.quit_confirm = ConfirmPopup(title='Quit?', confirm_text='Quit') self.quit_confirm.bind(on_confirm=self.quit_pushed) self.quit_confirm.bind(on_cancel=self.cancel_pushed) # there is some sort of instantiation order problem where you can't # directly refer to custom classes as children in the kv language, so # everywhere were we want custom classes there is a BoxLayout which we # will now put the custom classes inside self.menu = Menu() self.menu.hide_item('Chats') self.menu.bind(text=self.menu_action) self.ids.menu_container.add_widget(self.menu) self.chat_box = ChatBox() self.ids.chat_box_container.add_widget(self.chat_box) # don't add friend_box just yet, it has the connection status label in # it self.friend_box = FriendBox(self) store = JsonStore('storage.json') try: userid = store.get('account')['userid'] password = store.get('account')['password'] host = store.get('server')['host'] port = store.get('server')['port'] except KeyError: self.ids.connection_label.text = 'No Username Set' else: # create the chat client and start processing on separate thread self.chat_client = ChatClient(self, userid, password) self.chat_client.connect((host, port)) self.chat_client.process(block=False)
def main(argv): arg_len = len(argv) if arg_len < 2: return invalidargs(argv) elif argv[1] == "client": console = ChatConsole(name="Chat App") if(arg_len == 4): client = ChatClient(address=argv[2], port=argv[3]) elif(arg_len == 2): client = ChatClient() else: return invalidargs(argv) # worker = threading.Thread(target=client.start, # kwargs={"outputFx": console.receive_message}, # daemon=True) #_thread.start_new_thread(client.start, (), {"outputFx" : console.receive_message}) client.start(outputFx=console.receive_message) console.start(outputFx=client.send) return 1 elif argv[1] == "server": console = ChatConsole(name="Server Console") if(arg_len == 4): server = AuthenticatingChatServer(address=argv[2], port=argv[3]) elif(arg_len == 2): server = AuthenticatingChatServer() else: return invalidargs(argv) worker = threading.Thread(target=server.start, kwargs={"outputFx": console.receive_message}, daemon=True) worker.start() console.start(outputFx=server.server_console_input) return else: return invalidargs()
class RootBox(BoxLayout): def __init__(self, *args, **kwargs): super(RootBox, self).__init__(*args, **kwargs) self.chat_client = None self.receive_queue = Queue() # create the confirm box for quitting self.quit_confirm = ConfirmPopup(title='Quit?', confirm_text='Quit') self.quit_confirm.bind(on_confirm=self.quit_pushed) self.quit_confirm.bind(on_cancel=self.cancel_pushed) # there is some sort of instantiation order problem where you can't # directly refer to custom classes as children in the kv language, so # everywhere were we want custom classes there is a BoxLayout which we # will now put the custom classes inside self.menu = Menu() self.menu.hide_item('Chats') self.menu.bind(text=self.menu_action) self.ids.menu_container.add_widget(self.menu) self.chat_box = ChatBox() self.ids.chat_box_container.add_widget(self.chat_box) # don't add friend_box just yet, it has the connection status label in # it self.friend_box = FriendBox(self) store = JsonStore('storage.json') try: userid = store.get('account')['userid'] password = store.get('account')['password'] host = store.get('server')['host'] port = store.get('server')['port'] except KeyError: self.ids.connection_label.text = 'No Username Set' else: # create the chat client and start processing on separate thread self.chat_client = ChatClient(self, userid, password) self.chat_client.connect((host, port)) self.chat_client.process(block=False) def quit_pushed(self, *args): print 'Disconnecting...' if self.chat_client: self.chat_client.disconnect(wait=True) quit() def cancel_pushed(self, *args): # changed their mind about quitting, as our menu is not a real menu # but a spinner, we need to reset the display value to be our current # screen self.menu.text = self.ids.screen_manager.current def menu_action(self, spinner, text): if text == 'Quit': self.quit_confirm.open() elif text == 'Settings': app = App.get_running_app() app.open_settings() # settings uses a pop-up, need to set our spinner menu back to # wherever we were self.menu.text = self.ids.screen_manager.current elif text == 'Chats': # go to chat screen and clear the current tab's friend's message # count self.ids.screen_manager.current = text current_tab = self.chat_box.ids.tab_content.current try: self.chat_box.chats[current_tab]['friend'].message_count = 0 except KeyError: # there is no current tab, do nothing pass else: # switch to the screen chosen by the spinner self.ids.screen_manager.current = text def menu_add_chat(self): self.menu.show_item('Chats') def menu_remove_chat(self): self.menu.hide_item('Chats', select='Contacts') self.ids.screen_manager.current = 'Contacts'
class RootBox(BoxLayout): def __init__(self, *args, **kwargs): super(RootBox, self).__init__(*args, **kwargs) self.chat_client = None self.receive_queue = Queue() # create the confirm box for quitting self.quit_confirm = ConfirmPopup(title='Quit?', confirm_text='Quit') self.quit_confirm.bind(on_confirm=self.quit_pushed) self.quit_confirm.bind(on_cancel=self.cancel_pushed) # there is some sort of instantiation order problem where you can't # directly refer to custom classes as children in the kv language, so # everywhere were we want custom classes there is a BoxLayout which we # will now put the custom classes inside self.menu = Menu() self.menu.hide_item('Chats') self.menu.bind(text=self.menu_action) self.ids.menu_container.add_widget(self.menu) self.chat_box = ChatBox() self.ids.chat_box_container.add_widget(self.chat_box) # don't add friend_box just yet, it has the connection status label in # it self.friend_box = FriendBox(self) store = JsonStore('storage.json') try: userid = store.get('account')['userid'] password = store.get('account')['password'] host = store.get('server')['host'] port = store.get('server')['port'] except KeyError: self.ids.connection_label.text = 'No Username Set' else: # create the chat client and start processing on separate thread self.chat_client = ChatClient(self, userid, password) self.chat_client.connect((host, port)) self.chat_client.process(block=False) def quit_pushed(self, *args): print ('Disconnecting...') if self.chat_client: self.chat_client.disconnect(wait=True) quit() def cancel_pushed(self, *args): # changed their mind about quitting, as our menu is not a real menu # but a spinner, we need to reset the display value to be our current # screen self.menu.text = self.ids.screen_manager.current def menu_action(self, spinner, text): if text == 'Quit': self.quit_confirm.open() elif text == 'Settings': app = App.get_running_app() app.open_settings() # settings uses a pop-up, need to set our spinner menu back to # wherever we were self.menu.text = self.ids.screen_manager.current elif text == 'Chats': # go to chat screen and clear the current tab's friend's message # count self.ids.screen_manager.current = text current_tab = self.chat_box.ids.tab_content.current try: self.chat_box.chats[current_tab]['friend'].message_count = 0 except KeyError: # there is no current tab, do nothing pass else: # switch to the screen chosen by the spinner self.ids.screen_manager.current = text def menu_add_chat(self): self.menu.show_item('Chats') def menu_remove_chat(self): self.menu.hide_item('Chats', select='Contacts') self.ids.screen_manager.current = 'Contacts'
client.send("DISCONNECT") client.close_socket() top.quit() host = input('Enter host: ') port = input('Enter port: ') if not host: host = "localhost" if not port: port = 1234 else: port = int(port) client = ChatClient("Mauricio",host,port) client.init_socket() top = tkinter.Tk() top.title("PyChat: Chat built in Python") messages_frame = tkinter.Frame(top) my_msg = tkinter.StringVar() my_msg.set("") scrollbar = tkinter.Scrollbar(messages_frame) msg_list = tkinter.Listbox(messages_frame, height=30, width=100, yscrollcommand=scrollbar.set) scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y) msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH) msg_list.pack() messages_frame.pack() entry_field = tkinter.Entry(top, textvariable=my_msg)
from chatclient import ChatClient IP_ADDRESS = "127.0.0.1" PORT = 5500 if __name__ == "__main__": server = ChatClient(IP_ADDRESS, PORT) server.run()
class TestClient(unittest.TestCase): def setUp(self): self.server = socket(AF_INET, SOCK_STREAM) address = ('',1234) self.server.bind(address) self.server.listen() self.client = ChatClient("Mauricio","localhost",1234) self.client.init_socket() def tearDown(self): self.client.close_socket() self.server.close() def test_str_connected(self): self.assertEqual(self.client.__str__(),"Mauricio -> localhost:1234 [CONNECTED]") def test_str_disconnected(self): self.client.close_socket() self.assertEqual(self.client.__str__(),"Mauricio -> localhost:1234 [DISCONNECTED]") def test_get_username(self): self.assertIs(self.client.get_username(),self.client.username) def test_get_host(self): self.assertIs(self.client.get_host(),self.client.host) def test_get_port(self): self.assertIs(self.client.get_port(),self.client.port) def test_get_address(self): self.assertIs(self.client.get_address(),self.client.address) def test_get_socket(self): self.assertIs(self.client.get_socket(),self.client.client_socket) def test_get_status(self): self.assertEqual(self.client.get_status(),self.client.status) def test_set_username(self): username = "******" self.client.set_username(username) self.assertIs(username,self.client.username) def test_set_host(self): host = "127.0.0.8" self.client.set_host(host) self.assertIs(host,self.client.host) def test_set_port(self): port = 33000 self.client.set_port(port) self.assertIs(port,self.client.port) def test_set_address(self): address = ("127.0.2.0",12345) self.client.set_address(address) self.assertIs(address,self.client.address) def test_set_socket(self): self.client.close_socket() new_socket = socket(AF_INET, SOCK_STREAM) address = ("127.0.0.1",1234) new_socket.connect(address) self.client.set_socket(new_socket) self.assertIs(new_socket,self.client.client_socket) def test_set_socket_None(self): socket = None self.client.set_socket(socket) self.assertIs(socket,self.client.client_socket) def test_set_status(self): self.client.set_status("BUSY") self.assertEqual(self.client.status,"BUSY")
def setUp(self): self.client = ChatClient("Mauricio") self.client2 = ChatClient("Aglae") self.public_room = ChatRoom() self.private_room = ChatRoom(self.client, "foo", False)