class ChatCmdHandler(CmdHandler): def __init__(self): self.chat_client = ChatClient(self) self.conn = None pass def __conn_to_server(self, ip, port): init_client(self.chat_client, ip, port) def on_conn_made(self, conn): self.conn = conn self.__conn_to_server('localhost', 8888) pass def on_conn_lost(self, conn, reason): self.conn = None def on_msg(self, conn, msg): self.chat_client.on_cmd(msg) pass def on_client_msg(self, client, msg): # 从client传过来的数据 self.conn.sendLine(msg) pass
class ConsoleChat: def __init__(self, port=8888): self.chat = ChatClient(port, self.render_message, self.get_nickname) def iterate(self): self.chat.iterate() data = self.get_input() if data is not None: self.chat.send_message(data) @staticmethod def render_message(message): sys.stdout.write('\r') message = loads(message) sys.stdout.write('{}: {}\n'.format(message['nickname'], message['data'])) sys.stdout.write('> ') sys.stdout.flush() @staticmethod def get_nickname(): name = input('[Auth] Enter your nickname\n> ') return name @staticmethod def get_input(): stdin = [sys.stdin] ready_to_read, _, _ = select.select(stdin, [], [], 0) if len(ready_to_read) == 0: return None message = sys.stdin.readline() sys.stdout.write('\x1b[1A\r> ') sys.stdout.flush() return message
def __init__(self, server_name, server_port): self.__engine = ChatClient(server_name, server_port) self.root = tkinter.Tk() self.root.title('Chat: %s' % str(self.__engine.get_name())) width = 400 height = 600 screen_width = self.root.winfo_screenwidth() screen_height = self.root.winfo_screenheight() self.root.geometry("{width}x{height}+{x}+{y}".format( width=width, height=height, x=int((screen_width - width) / 2), y=int((screen_height - height - 50) / 2))) label_frame_new_message_height = 50 margin = 5 self.text_messages = tkinter.Text(self.root) self.text_messages.config(state=tkinter.DISABLED) self.text_messages.place(width=-2 * margin, height=-3 * margin - label_frame_new_message_height, relwidth=1, relheight=1, x=margin, y=margin, relx=0, rely=0) label_frame_new_message = tkinter.LabelFrame(self.root, text='New Message') label_frame_new_message.place(width=-2 * margin, height=label_frame_new_message_height, x=margin, y=-label_frame_new_message_height - margin, relwidth=1, relheight=0, relx=0, rely=1) button_send_width = 37 self.__button_send = tkinter.Button(label_frame_new_message, text='Send', command=self.__send_message) self.__button_send.place(x=-button_send_width - margin, y=0, relx=1) self.__entry_message = tkinter.Entry(label_frame_new_message) self.__entry_message.focus() self.__entry_message.bind('<Return>', lambda x: self.__send_message()) self.__entry_message.place(width=-button_send_width - 3 * margin, x=margin, y=margin, relwidth=1) receive_message_thread = Thread(target=self.__received_message) receive_message_thread.start() self.root.mainloop()
class ConsoleChat: def __init__(self, port=8888): self.chat = ChatClient(port, self.render_message, self.get_nickname) def iterate(self): self.chat.iterate() data = self.get_input() if data is not None: self.chat.send_message(data) @staticmethod def render_message(message): sys.stdout.write('\r') message = loads(message) sys.stdout.write('{}: {}\n'.format(message['nickname'], message['data'])) sys.stdout.write('> ') sys.stdout.flush() @staticmethod def get_nickname(): name = input('[Auth] Enter your nickname\n> ') return name @staticmethod def get_input(): stdin = [sys.stdin] ready_to_read, _, _ = select.select(stdin, [], [], 0) if len(ready_to_read) == 0: return None message = sys.stdin.readline() sys.stdout.write('\x1b[1A\r> ') sys.stdout.flush() return message
class ChatThread(QtCore.QThread): def __init__(self, port, render_message, get_nickname): QtCore.QThread.__init__(self) self.chat = ChatClient(port, render_message, get_nickname) def run(self): while True: self.chat.iterate() def send_message(self, message): self.chat.send_message(message)
class ChatThread(QtCore.QThread): def __init__(self, port, render_message, get_nickname): QtCore.QThread.__init__(self) self.chat = ChatClient(port, render_message, get_nickname) def run(self): while True: self.chat.iterate() def send_message(self, message): self.chat.send_message(message)
def chat_factory(args): ACTION_SERVE = 'serve' ACTION_CONNECT = 'connect' if args.action.lower() == ACTION_SERVE: return ChatServer(args) if args.action.lower() == ACTION_CONNECT: return ChatClient(args)
def run(self): print('Server is runing on {}'.format(self.port)) while True: conn, addr = self.server.accept() client = ChatClient(conn, addr) self.client_pool.append(client) threading.Thread(target=self.run_thread, args=(client, ), daemon=True).start()
def run(self): print('Server running on {}'.format(PORT)) while True: conn, addr = self.server.accept() client = ChatClient(conn, addr) self.client_pool.append(client) Thread(target=self.run_thread, args=(client.id, client.nick, client.conn, client.addr), daemon=True).start()
def run(self): """ Accept connections, add to client_pool, start thread """ print('Server running on {} : {}'.format(self.host, PORT)) while True: conn, addr = self.server.accept() client = ChatClient(conn, addr) self.client_pool.append(client) Thread(target=self.run_thread, args=(client.id, client.nick, client.conn, client.addr), daemon=True).start()
def run(self): """This method uses an infinite loop to keep the chatroom open if called. """ print('Server is running on {}'.format(self.port)) while True: conn, addr = self.server.accept() client = ChatClient(conn, addr) self.client_pool.append(client) threading.Thread(target=self.run_thread, args=(client, ), daemon=True).start() pass
def run(self): """Once this method is run, the server will start and find the connection. While true, the address and client will stay connected. Once all these arguments are taken into account, the server will start. """ print('Server running on {}'.format(PORT)) while True: conn, addr = self.server.accept() client = ChatClient(conn, addr) self.client_pool.append(client) threading.Thread(target=self.run_thread, args=(client, ), daemon=True).start()
def __init__(self, port=8888): self.chat = ChatClient(port, self.render_message, self.get_nickname)
class ChatClientGUI: def __init__(self, server_name, server_port): self.__engine = ChatClient(server_name, server_port) self.root = tkinter.Tk() self.root.title('Chat: %s' % str(self.__engine.get_name())) width = 400 height = 600 screen_width = self.root.winfo_screenwidth() screen_height = self.root.winfo_screenheight() self.root.geometry("{width}x{height}+{x}+{y}".format( width=width, height=height, x=int((screen_width - width) / 2), y=int((screen_height - height - 50) / 2))) label_frame_new_message_height = 50 margin = 5 self.text_messages = tkinter.Text(self.root) self.text_messages.config(state=tkinter.DISABLED) self.text_messages.place(width=-2 * margin, height=-3 * margin - label_frame_new_message_height, relwidth=1, relheight=1, x=margin, y=margin, relx=0, rely=0) label_frame_new_message = tkinter.LabelFrame(self.root, text='New Message') label_frame_new_message.place(width=-2 * margin, height=label_frame_new_message_height, x=margin, y=-label_frame_new_message_height - margin, relwidth=1, relheight=0, relx=0, rely=1) button_send_width = 37 self.__button_send = tkinter.Button(label_frame_new_message, text='Send', command=self.__send_message) self.__button_send.place(x=-button_send_width - margin, y=0, relx=1) self.__entry_message = tkinter.Entry(label_frame_new_message) self.__entry_message.focus() self.__entry_message.bind('<Return>', lambda x: self.__send_message()) self.__entry_message.place(width=-button_send_width - 3 * margin, x=margin, y=margin, relwidth=1) receive_message_thread = Thread(target=self.__received_message) receive_message_thread.start() self.root.mainloop() def __received_message(self): while True: message = self.__engine.receive_message() print(message) if message is None: break self.text_messages.config(state=tkinter.NORMAL) self.text_messages.insert(tkinter.END, message.decode('utf-8') + '\n') self.text_messages.config(state=tkinter.DISABLED) def __send_message(self): print('send') message = self.__entry_message.get() self.__engine.send_message(message.encode('ascii')) self.__entry_message.delete(0, tkinter.END) def __close(self): self.root.quit() self.__engine.close()
def do_chat(user, server, input_file): cc = ChatClient() cc.user = user cc.server_hostname = server cc.connect_socket() cc.chat_from_file(input_file, delay=0.05)
def login(username): os.system("clear") c = ChatClient() if c.connect(username): sys.stdout.write("\x1b]2;%s\x07" % (c.username)) try: while c.connected == 1: msg = raw_input() msg = msg.strip() print "\033[A \033[A" if(len(msg)==0): continue try: cmd , temp = filter_message(msg) if cmd==-2: c.disconnect() clear_screen("Disconnecting...") break elif cmd==1: if len(msg.split(' ')) == 1: print bcolors.warning_message("~ChatUs~ : ") + bcolors.whisper_message("user %s is online" % (temp)) else: print bcolors.whisper_message("<You> : %s" % (msg)) c.say(msg) elif cmd==11: c.say(temp) print bcolors.whisper_message("<You> : Send file to %s" % (msg)) elif cmd==-1: print bcolors.warning_message("~ChatUs~ : ") + bcolors.fail_message("user %s is offline" % (temp)) elif cmd==2: print_list() elif cmd==3: if temp != '': c.say(temp) else: if(len(msg)>=1): print bcolors.normal_message("<You> : %s" % (msg)) c.say(msg) except: break except KeyboardInterrupt: c.disconnect() clear_screen("Disconnecting...") else: clear_screen("Server is offline")
def __init__(self): self.user = Interface.getUserId() self.client = ChatClient(self.user)
def __init__(self): self.chat_client = ChatClient(self) self.conn = None pass
class Interface: USER_MAX_SIZE = 15 HELP_STR = \ ''' help - see this menu users - display all users and their status ls - list all conversations open [-d] <NAME>[,...,<NAME>] - display conversation ('-d' for dates) send <NAME>[,...,<NAME>] <MESSAGE> - send a message to user bcast <MESSAGE> - send a message to everyone exit - exit the program ''' HELP_CMD = 'help' USERS_CMD = 'users' LS_CMD = 'ls' OPEN_CMD = 'open' SEND_CMD = 'send' BCAST_CMD = 'bcast' EXIT_CMD = 'exit' CONV_DELIM = ',' def __init__(self): self.user = Interface.getUserId() self.client = ChatClient(self.user) @staticmethod def getUserId(): print() user = '' while user == '' or len(user) > Interface.USER_MAX_SIZE: user = input('user: '******'[\s+]', '', user ) # TODO replace all characters that are invalid in a topic name if len(user) > Interface.USER_MAX_SIZE: print('user must < %s characters' % Interface.USER_MAX_SIZE) print() return user @staticmethod def buildTimestamp(value): datestamp = date.fromtimestamp(value // 1000) timestamp = time.strftime('%H:%M:%S', time.gmtime(value / 1000 - 28800)) return datestamp, timestamp def run(self): shutdown = False while not shutdown: # prompt print(self.user + ' > ', end='') line = input() if line == '': continue # parse into array (& allow use of quotes) cmd = [ re.sub('["\']', '', c[0]) for c in re.findall('([^\'"]\\S*|([\'"]).+?\\2)\\s*', line) ] def invalidCmd(c): print('error: invalid use of \'%s\'; see \'help\' menu' % c) if cmd[0] == self.HELP_CMD: # help print(self.HELP_STR) elif cmd[0] == self.USERS_CMD: # users users = self.client.getUsers() for i in users: datestamp, timestamp = self.buildTimestamp( users[i].timestamp) online = users[i].isOnline if online == "online": print("{:10} | Status: \u001b[32m{}\u001b[0m".format( i, online)) else: print("{:10} | Status: \u001b[31m{}\u001b[0m".format( i, online)) elif cmd[0] == self.LS_CMD: # ls print(self.client.listConversations()) elif cmd[0] == self.OPEN_CMD: # open [-d] <NAME>[,...,<NAME>] if len(cmd) < 2: invalidCmd(cmd[0]) else: showTime = False userList = None for arg in cmd[1:]: if arg.lower() == '-d': showTime = True else: userList = re.split(',', arg) for mes in self.client.getConversation(userList): json_obj = json.loads(mes.message) user = json_obj["from"] content = json_obj["message"] if showTime: datestamp, timestamp = self.buildTimestamp( mes.timestamp) print( "{} {} | \u001b[34m{:10}\u001b[0m | {}".format( datestamp, timestamp, user, content)) else: print("\u001b[34m{:10}\u001b[0m | {}".format( user, content)) pass elif cmd[0] == self.SEND_CMD: # send <NAME>[,...,<NAME>] <MESSAGE> if len(cmd) < 3: invalidCmd(cmd[0]) else: sendTo = [s for s in re.split(self.CONV_DELIM, cmd[1])] self.client.sendMessage(sendTo, cmd[2]) elif cmd[0] == self.BCAST_CMD: # bcast <MESSAGE> if len(cmd) < 2: invalidCmd(cmd[0]) else: self.client.sendMessage(['GLOBAL'], cmd[1]) elif cmd[0] == self.EXIT_CMD: shutdown = True self.client.shutdown()
def do_chat(user, server, input_file): cc = ChatClient() cc.user = user cc.server_hostname = server cc.connect_socket() cc.chat_from_file(input_file, delay=0.05)
def main(): client = ChatClient() client.get_user_input()
def __init__(self, port, name): super().__init__() self.signal.connect(self.recv_thread) self.signal2.connect(self.update_names) self.chat = ChatClient(port, name, self.signal, self.signal2) self.button = QtWidgets.QPushButton("Send") self.button.clicked.connect(self.on_click) self.button.setAutoDefault(True) self.text_view = QtWidgets.QTextEdit() self.text_view.setText('<html></html>') self.text_view.setReadOnly(True) self.text_view.setLineWrapMode(QtWidgets.QTextEdit.NoWrap) self.text = '<html></html>' self.users = QtWidgets.QTextEdit() self.users.sizeHint = self.users_hint self.users.setReadOnly(True) self.users.setLineWrapMode(QtWidgets.QTextEdit.NoWrap) self.users.resize(10, 10) self.user_names = ('<html>' + '<font color="red">{}</font><br/>'.format(name) + '</html>') self.users.setText(self.user_names) self.input = QtWidgets.QLineEdit() #pragma mark - formatting buttons self.bold = self.create_image_button('bold') self.strike = self.create_image_button('strike') self.italic = self.create_image_button('italic') self.underline = self.create_image_button('underline') self.sup = self.create_image_button('sup') self.sub = self.create_image_button('sub') self.quote1 = self.create_image_button('quote1') #pragma mark - emoji self.moon = PicButton(QtGui.QPixmap("emoji/{}.png".format('moon'))) self.moon.clicked.connect(lambda: self.mark('*{}*'.format('moon'))) self.sun = PicButton(QtGui.QPixmap("emoji/{}.png".format('sun'))) self.sun.clicked.connect(lambda: self.mark('*{}*'.format('sun'))) self.zefirchik = PicButton(QtGui.QPixmap("emoji/{}.png".format('zefirchik'))) self.zefirchik.clicked.connect(lambda: self.mark('*{}*'.format('zefirchik'))) self.cry = PicButton(QtGui.QPixmap("emoji/{}.png".format('cry'))) self.cry.clicked.connect(lambda: self.mark('*{}*'.format('cry'))) self.main_layout = QtWidgets.QGridLayout() self.main_layout.addWidget(self.input, 0, 0, 1, 50) self.main_layout.addWidget(self.button, 0, 50, 1, 10) self.main_layout.addWidget(self.bold) self.main_layout.addWidget(self.strike) self.main_layout.addWidget(self.italic) self.main_layout.addWidget(self.underline) self.main_layout.addWidget(self.sup) self.main_layout.addWidget(self.sub) self.main_layout.addWidget(self.quote1) self.main_layout.addWidget(self.moon, 2, 0) self.main_layout.addWidget(self.sun) self.main_layout.addWidget(self.zefirchik) self.main_layout.addWidget(self.cry) self.main_layout.addWidget(self.text_view, 3, 0, 1, 50) self.main_layout.addWidget(self.users, 3, 50, 1, 10) self.setLayout(self.main_layout)
class ChatWindow(QtWidgets.QWidget): """ Main class of chat GUI """ signal = QtCore.pyqtSignal(str) signal2 = QtCore.pyqtSignal(list) allowed_tags = {'bold': '<b></b>', 'strike': '<s></s>', 'italic': '<i></i>', 'overline': '<o></o>', 'underline': '<u></u>', 'sup': '<sup></sup>', 'sub': '<sub></sub>', 'quote1': '>'} tag_buttons = [] emoji = ['moon', 'sun', 'zefirchik', 'cry'] emoji_buttons = [] pic = '<img src="emoji/{}" width=16 height=16>' def __init__(self, port, name): super().__init__() self.signal.connect(self.recv_thread) self.signal2.connect(self.update_names) self.chat = ChatClient(port, name, self.signal, self.signal2) self.button = QtWidgets.QPushButton("Send") self.button.clicked.connect(self.on_click) self.button.setAutoDefault(True) self.text_view = QtWidgets.QTextEdit() self.text_view.setText('<html></html>') self.text_view.setReadOnly(True) self.text_view.setLineWrapMode(QtWidgets.QTextEdit.NoWrap) self.text = '<html></html>' self.users = QtWidgets.QTextEdit() self.users.sizeHint = self.users_hint self.users.setReadOnly(True) self.users.setLineWrapMode(QtWidgets.QTextEdit.NoWrap) self.users.resize(10, 10) self.user_names = ('<html>' + '<font color="red">{}</font><br/>'.format(name) + '</html>') self.users.setText(self.user_names) self.input = QtWidgets.QLineEdit() #pragma mark - formatting buttons self.bold = self.create_image_button('bold') self.strike = self.create_image_button('strike') self.italic = self.create_image_button('italic') self.underline = self.create_image_button('underline') self.sup = self.create_image_button('sup') self.sub = self.create_image_button('sub') self.quote1 = self.create_image_button('quote1') #pragma mark - emoji self.moon = PicButton(QtGui.QPixmap("emoji/{}.png".format('moon'))) self.moon.clicked.connect(lambda: self.mark('*{}*'.format('moon'))) self.sun = PicButton(QtGui.QPixmap("emoji/{}.png".format('sun'))) self.sun.clicked.connect(lambda: self.mark('*{}*'.format('sun'))) self.zefirchik = PicButton(QtGui.QPixmap("emoji/{}.png".format('zefirchik'))) self.zefirchik.clicked.connect(lambda: self.mark('*{}*'.format('zefirchik'))) self.cry = PicButton(QtGui.QPixmap("emoji/{}.png".format('cry'))) self.cry.clicked.connect(lambda: self.mark('*{}*'.format('cry'))) self.main_layout = QtWidgets.QGridLayout() self.main_layout.addWidget(self.input, 0, 0, 1, 50) self.main_layout.addWidget(self.button, 0, 50, 1, 10) self.main_layout.addWidget(self.bold) self.main_layout.addWidget(self.strike) self.main_layout.addWidget(self.italic) self.main_layout.addWidget(self.underline) self.main_layout.addWidget(self.sup) self.main_layout.addWidget(self.sub) self.main_layout.addWidget(self.quote1) self.main_layout.addWidget(self.moon, 2, 0) self.main_layout.addWidget(self.sun) self.main_layout.addWidget(self.zefirchik) self.main_layout.addWidget(self.cry) self.main_layout.addWidget(self.text_view, 3, 0, 1, 50) self.main_layout.addWidget(self.users, 3, 50, 1, 10) self.setLayout(self.main_layout) @staticmethod def users_hint(): """ Sets size hint for users field """ return QtCore.QSize(100, 300) def mark(self, tag): """ Sets appropriate tags for emoji and markdown """ self.input.setText(self.input.text() + tag) def on_click(self): """ Sends text from input to client """ text = html_parse.get_correct_html(self.input.text()) if html_parse.has_any_text(text): for emoj in self.emoji: text = text.replace('*{}*'.format(emoj), self.pic.format(emoj)) if text[0] == '>': text = '<font color="green">{}</font>'.format(text) self.text = (self.text[:-7] + '<font color="red">{}</font>'.format(self.chat.client.nickname) + ": " + text + '<br/></html>') self.text_view.setText(self.text) self.chat.send_from_input(text) self.text_view.moveCursor(QtGui.QTextCursor.End) self.input.setText('') def keyPressEvent(self, event): """ Overrides keyPressEvent; Send button is clicked when enter is pressed """ if event.key() == QtCore.Qt.Key_Return: self.on_click() else: super().keyPressEvent(event) @QtCore.pyqtSlot(str) def recv_thread(self, status): """ Updates text view when needed """ self.text = self.text[:-7] + status + '<br/></html>' self.text_view.setText(self.text) @QtCore.pyqtSlot(list) def update_names(self, names): """ Updates names field when needed """ self.user_names = '<html>' for name in names: if name == self.chat.client.nickname: self.user_names += '<font color="red">{}</font><br/>'.format(name) else: self.user_names += name + '<br/>' self.user_names += '</html>' self.users.setText(self.user_names) def create_image_button(self, tag): """ Method for creating button with image """ button = PicButton(QtGui.QPixmap("mark/{}.png".format(tag))) button.clicked.connect(lambda: self.mark(self.allowed_tags[tag])) button.setMaximumWidth(16) return button
def __init__(self, port, render_message, get_nickname): QtCore.QThread.__init__(self) self.chat = ChatClient(port, render_message, get_nickname)
def __init__(self, port, render_message, get_nickname): QtCore.QThread.__init__(self) self.chat = ChatClient(port, render_message, get_nickname)
def __init__(self, port=8888): self.chat = ChatClient(port, self.render_message, self.get_nickname)
def manage_login(self, message): client = ChatClient(message["nickname"], message["room"], message["connectedAt"]) client.connection = self ChatWebSocketHandler.clients.append(client)