class TCPConnection(QThread): connected = pyqtSignal(bool) message = pyqtSignal(str) def __init__(self, parent=None): super().__init__(parent) self.ip = "127.0.0.1" self.port = 4040 self.username = None self.message_queue = Queue() self.client = TCPClient(self.ip, self.port, 2048) self.client.add_handler(ON_MESSAGE, self.message.emit) def connect(self): try: self.client.connect() return True except ConnectionRefusedError: return False def send_message(self, message): self.message_queue.put(f"{self.username}: {message}") def run(self): conn_status = self.connect() self.connected.emit(conn_status) if conn_status: self.client.send(f"{self.username} has joined!") self.client.start() while True: if not self.message_queue.empty(): self.client.send(self.message_queue.get())
def __init__(self, parent=None): super().__init__(parent) self.ip = "127.0.0.1" self.port = 4040 self.username = None self.message_queue = Queue() self.client = TCPClient(self.ip, self.port, 2048) self.client.add_handler(ON_MESSAGE, self.message.emit)
class TrackBot(object): def __init__(self, host, port, buffer_size, imei=""): self.client = TCPClient(host, port, buffer_size) self.imei = imei self.location = Point((0, 0)) @staticmethod def get_random_location(): return Point(( random.uniform(20, 26), random.uniform(88, 92) )) def move_randomly(self): multiplier = random.choice([1, -1]) lat = self.location['coordinates'][0] + (random.random() / 100 * multiplier) lon = self.location['coordinates'][1] + (random.random() / 100 * multiplier) self.location = Point((lat, lon)) def ping_tcp(self, point): message = 'lat={},lon={},imei={}'.format( point['coordinates'][0], point['coordinates'][1], self.imei ) self.client.send_message(message) time.sleep(5) def ping_tcp_random(self): if self.location['coordinates'][0] == 0 \ and self.location['coordinates'][1] == 0: self.location = TrackBot.get_random_location() self.move_randomly() self.ping_tcp(self.location) @staticmethod def ping_api(user_id, name, point): data = { 'user_id': user_id, 'name': name, 'point': point } url = 'http://localhost:5000/api/ping' response = requests.post(url, json=data) return response.json() def ping_api_random(self, user_id, name): if self.location['coordinates'][0] == 0 \ and self.location['coordinates'][1] == 0: self.location = TrackBot.get_random_location() self.move_randomly() return self.ping_api(user_id, name, self.location)
def connClicked(self): sendIP = self.txtSendIP.text() sendPort = self.txtSendPort.text() try: TCPClient(sendIP, sendPort).send(("testConn", ()), self.connCallBack) except Exception as e: print(e) self.txtConsole.append(str(e))
def showUserListTable(self): users = TCPClient().send(("getUsers",())) print(users) try: if users != None: index = 0 for user in users: self.createUserListTableRow(index, user) index += 1 except Exception as e: print("Show user list table failed.", e)
def login(self): name = self.ui_login.txt_name.text() password = self.ui_login.txt_password.text() user = TCPClient().send(("getUserByName", (name,))) if user != None and user[2] == password: self.user = user self.MainWindow.show() self.Dialog.close() self.showUserListTable() return True else: return False
def run(self): print(intro) while self.running == True: choice = input("\n >") if choice == '3': self.running = False elif choice == '2': TCPClient().ClientInterface() self.running = False break elif choice == '1': ServerInterface().ChatRoomInterface() self.running = False break else: print("\nINVALID CHOICE")
def __init__(self): self.root = tk.Tk() # create window # self.root.attributes("-toolwindow", 1) # self.root.wm_attributes("-topmost", 1) self.root.title("Hi Chat") self.root.geometry("900x700+300+100") self.root.resizable(0, 0) self.username = None self.chat_with = '' self.chat_with_windows = {} self.output = None self.client = TCPClient() self.receive_queue = PriorityQueue() self.imgs = [] self.root.protocol("WM_DELETE_WINDOW", self.on_closing) # header提示语 self.frame_header = tk.Frame(self.root, bg='white') self.frame_header.place(x=0, y=0, width=900, height=30) self.hello_label = tk.Label(self.frame_header, text='', font=('仿宋', 20)) self.hello_label.place(x=700, y=0) self.chat_with_label = tk.Label(self.frame_header, text=f'{self.chat_with}', font=('仿宋', 20), bg='#66FFFF') self.chat_with_label.place(x=240, y=0, width=150) # 好友栏 self.canvas_right_bar = tk.Canvas(self.root, scrollregion=(0, 0, 250, 2000)) self.canvas_right_bar.place(x=650, y=30, width=250, height=620) self.right_scroll_bar = tk.Scrollbar( self.canvas_right_bar, orient='vertical', command=self.canvas_right_bar.yview) self.right_scroll_bar.pack(side='left', fill=tk.Y) self.canvas_right_bar.config(yscrollcommand=self.right_scroll_bar.set) self.frame_right_bar = tk.Frame(self.canvas_right_bar, bg='#C0C0C0') self.frame_right_bar.place(x=0, y=0) self.canvas_right_bar.create_window(20, 0, anchor='nw', window=self.frame_right_bar) self.groups = {} self.friend_users = set() self.unread_message_num = {} # 好友栏下部按钮 self.frame_right_bottem = tk.Frame(self.root) self.frame_right_bottem.place(x=650, y=650, width=250, height=50) self.btn_add_user = tk.Button(self.frame_right_bottem, text='添加用户', font=('仿宋', 18), bg='#00CCCC', command=self.btn_add_user_event) self.btn_add_user.place(x=10, y=0) self.btn_add_group = tk.Button(self.frame_right_bottem, text='管理群组', font=('仿宋', 18), bg='#FF6699', command=self.btn_add_group_event) self.btn_add_group.place(x=120, y=0) # 聊天框 self.frame_chat = tk.Frame(self.root, bg='white') self.frame_chat.place(x=0, y=30, width=650, height=520) # self.output = tk.Text(self.frame_chat, state=tk.NORMAL, font=('仿宋', 20)) # self.output.place(x=0, y=0, width=650, height=520) # self.output.tag_config('sending', background="#0B5FA5", foreground="white") # self.output.tag_config('receiving', background='gray', foreground='white') self.output_scroll_bar = tk.Scrollbar(self.frame_chat, orient='vertical') self.output_scroll_bar.pack(side='right', fill=tk.Y) # self.output.config(yscrollcommand=self.output_scroll_bar.set, state=tk.DISABLED) # 输入框 self.frame_user_input = tk.Frame(self.root) self.frame_user_input.place(x=0, y=520, width=650, height=180) self.user_input = tk.Text(self.frame_user_input, font=('仿宋', 18)) self.user_input.bind('<Return>', self.enter_key_event) self.user_input.place(x=0, y=0, width=630, height=130) self.btn_user_input_ok = tk.Button( self.frame_user_input, text='发送', font=('仿宋', 18), bg='#99FF99', command=lambda: self.btn_get_text_data_event(self.user_input)) self.btn_user_input_ok.place(x=560, y=130) self.btn_user_input_browse = tk.Button(self.frame_user_input, text='文件', font=('仿宋', 18), bg='#66FFFF', command=self.ask_open_file) self.btn_user_input_browse.place(x=470, y=130) self.btn_clear_output = tk.Button(self.frame_user_input, text='清屏', font=('仿宋', 18), bg='#FF6633', command=self.btn_clear_output_event) self.btn_clear_output.place(x=380, y=130)
class MainPanel(): def __init__(self): self.root = tk.Tk() # create window # self.root.attributes("-toolwindow", 1) # self.root.wm_attributes("-topmost", 1) self.root.title("Hi Chat") self.root.geometry("900x700+300+100") self.root.resizable(0, 0) self.username = None self.chat_with = '' self.chat_with_windows = {} self.output = None self.client = TCPClient() self.receive_queue = PriorityQueue() self.imgs = [] self.root.protocol("WM_DELETE_WINDOW", self.on_closing) # header提示语 self.frame_header = tk.Frame(self.root, bg='white') self.frame_header.place(x=0, y=0, width=900, height=30) self.hello_label = tk.Label(self.frame_header, text='', font=('仿宋', 20)) self.hello_label.place(x=700, y=0) self.chat_with_label = tk.Label(self.frame_header, text=f'{self.chat_with}', font=('仿宋', 20), bg='#66FFFF') self.chat_with_label.place(x=240, y=0, width=150) # 好友栏 self.canvas_right_bar = tk.Canvas(self.root, scrollregion=(0, 0, 250, 2000)) self.canvas_right_bar.place(x=650, y=30, width=250, height=620) self.right_scroll_bar = tk.Scrollbar( self.canvas_right_bar, orient='vertical', command=self.canvas_right_bar.yview) self.right_scroll_bar.pack(side='left', fill=tk.Y) self.canvas_right_bar.config(yscrollcommand=self.right_scroll_bar.set) self.frame_right_bar = tk.Frame(self.canvas_right_bar, bg='#C0C0C0') self.frame_right_bar.place(x=0, y=0) self.canvas_right_bar.create_window(20, 0, anchor='nw', window=self.frame_right_bar) self.groups = {} self.friend_users = set() self.unread_message_num = {} # 好友栏下部按钮 self.frame_right_bottem = tk.Frame(self.root) self.frame_right_bottem.place(x=650, y=650, width=250, height=50) self.btn_add_user = tk.Button(self.frame_right_bottem, text='添加用户', font=('仿宋', 18), bg='#00CCCC', command=self.btn_add_user_event) self.btn_add_user.place(x=10, y=0) self.btn_add_group = tk.Button(self.frame_right_bottem, text='管理群组', font=('仿宋', 18), bg='#FF6699', command=self.btn_add_group_event) self.btn_add_group.place(x=120, y=0) # 聊天框 self.frame_chat = tk.Frame(self.root, bg='white') self.frame_chat.place(x=0, y=30, width=650, height=520) # self.output = tk.Text(self.frame_chat, state=tk.NORMAL, font=('仿宋', 20)) # self.output.place(x=0, y=0, width=650, height=520) # self.output.tag_config('sending', background="#0B5FA5", foreground="white") # self.output.tag_config('receiving', background='gray', foreground='white') self.output_scroll_bar = tk.Scrollbar(self.frame_chat, orient='vertical') self.output_scroll_bar.pack(side='right', fill=tk.Y) # self.output.config(yscrollcommand=self.output_scroll_bar.set, state=tk.DISABLED) # 输入框 self.frame_user_input = tk.Frame(self.root) self.frame_user_input.place(x=0, y=520, width=650, height=180) self.user_input = tk.Text(self.frame_user_input, font=('仿宋', 18)) self.user_input.bind('<Return>', self.enter_key_event) self.user_input.place(x=0, y=0, width=630, height=130) self.btn_user_input_ok = tk.Button( self.frame_user_input, text='发送', font=('仿宋', 18), bg='#99FF99', command=lambda: self.btn_get_text_data_event(self.user_input)) self.btn_user_input_ok.place(x=560, y=130) self.btn_user_input_browse = tk.Button(self.frame_user_input, text='文件', font=('仿宋', 18), bg='#66FFFF', command=self.ask_open_file) self.btn_user_input_browse.place(x=470, y=130) self.btn_clear_output = tk.Button(self.frame_user_input, text='清屏', font=('仿宋', 18), bg='#FF6633', command=self.btn_clear_output_event) self.btn_clear_output.place(x=380, y=130) def read_groups_data(self): if file_exist(self.username + '/log.dat'): with open(self.username + '/log.dat', 'rb') as file: self.groups = pickle.load(file) else: self.create_new_group('default') def shift_chat_with_window(self, username=None): if not username: username = self.username self.chat_with = '' else: self.chat_with = username self.output = self.chat_with_windows[username] self.output.config(state=tk.DISABLED, yscrollcommand=self.output_scroll_bar.set) self.output_scroll_bar.config(command=self.output.yview) self.output.yview(tk.END) self.output.tkraise() self.chat_with_label.config(text=self.chat_with) def click_user_to_chat_event(self, event): widget = event.widget try: index = int(widget.curselection()[0]) except: return None temp = widget.get(index).split(' 未读') if temp[1] != '0': widget.delete(index) widget.insert(index, f"{temp[0]} 未读0") widget.select_set(index) temp = temp[0] self.unread_message_num[temp] = 0 if self.chat_with != temp: self.shift_chat_with_window(temp) def btn_group_show_friends(self, group): group = self.groups[group] if group[2] == 0: if (len(group[0])) == 0: return None temp = tk.Listbox(group[1], font=('仿宋', 18)) temp.bind('<<ListboxSelect>>', self.click_user_to_chat_event) for user in group[0]: temp.insert('end', f"{user} 未读{self.unread_message_num[user]}") temp.pack() group[2] = temp else: group[2].destroy() group[2] = 0 self.update_groups() self.shift_chat_with_window(None) def btn_add_user_event(self): user_window = AddUserPanel(self.root, self.groups, self.client, self.update_groups) self.update_groups() def btn_add_group_event(self): for g, val in self.groups.items(): if val[2] != 0: self.btn_group_show_friends(g) group_window = GroupManagePanel(self, self.groups) group_window.run() self.update_groups() def btn_clear_output_event(self): if isinstance(self.output, tk.Text): self.output.config(state=tk.NORMAL) self.output.delete('1.0', tk.END) self.output.config(state=tk.DISABLED) def ask_open_file(self): if self.chat_with == '': messagebox.showerror(message='请先指定联系人,再发送消息', parent=self.root) return None file = filedialog.askopenfile(mode='rb', ) if file == None: return None file = file.read() temp = MessageNode('pic', time.time(), file, self.username, self.chat_with) self.output_one_message(temp, sending=True) self.client.send_queue.put(temp) def btn_get_text_data_event(self, text: tk.Text): if self.chat_with == '': messagebox.showerror(message='请先指定联系人,再发送消息', parent=self.root) return None text_content = text.get('1.0', tk.END).strip('\n').strip(' ') text.delete('1.0', tk.END) if len(text_content) == 0: return None temp = MessageNode('text', time.time(), text_content, self.username, self.chat_with) self.output_one_message(temp, sending=True) self.client.send_queue.put(temp) def enter_key_event(self, event): self.btn_get_text_data_event(self.user_input) return 'break' def create_chat_with_text_window(self, usr): if usr not in self.chat_with_windows: self.chat_with_windows[usr] = tk.Text( self.frame_chat, state=tk.DISABLED, font=('仿宋', 20), yscrollcommand=self.output_scroll_bar.set) self.chat_with_windows[usr].place(x=0, y=0, width=630, height=520) self.chat_with_windows[usr].tag_config('sending', background="#0B5FA5", foreground="white") self.chat_with_windows[usr].tag_config('receiving', background='gray', foreground='white') if isinstance(self.output, tk.Text): self.output.tkraise() def create_new_group(self, group_name: str): frm = tk.Frame(self.frame_right_bar) btn = tk.Button( frm, text=f"{group_name} 未读0", width=23, height=2, bg='#FFFF99', command=lambda: self.btn_group_show_friends(group_name)) btn.pack() self.groups[group_name] = [[], frm, 0] def get_group_button(self, group_name): frm: tk.Frame = self.groups[group_name][1] return frm.winfo_children()[0] def update_groups(self): self.update_friend_users() # self.groups['default'][1].pack() for key, val in self.groups.items(): [self.create_chat_with_text_window(x) for x in val[0]] if val[1] == None: temp = val[0].copy() self.create_new_group(key) self.groups[key][0] = temp self.groups[key][1].pack(fill='both') def update_friend_users(self): self.friend_users.clear() for key, val in self.groups.items(): [self.friend_users.add(x) for x in val[0]] for x in self.friend_users: if x not in self.unread_message_num: self.unread_message_num[x] = 0 def update_unread_message(self): for key, val in self.groups.items(): unread_sum = 0 for x in val[0]: unread_sum += self.unread_message_num[x] self.get_group_button(key).config(text=f"{key} 未读{unread_sum}") if val[2] == 0: continue else: try: index = int(val[2].curselection()[0]) except: index = None val[2].delete(0, 'end') for usr in val[0]: val[2].insert('end', f"{usr} 未读{self.unread_message_num[usr]}") if index: val[2].select_set(index) def output_one_message(self, data: MessageNode, sending=False): header, msg = data.get_output(sending) if sending: temp = data.receiver out_window = self.chat_with_windows[temp] out_window.config(state=tk.NORMAL) out_window.insert(tk.END, header, 'sending') else: temp = data.sender if self.chat_with != temp: self.unread_message_num[temp] += 1 out_window = self.chat_with_windows[temp] out_window.config(state=tk.NORMAL) out_window.insert(tk.END, header, 'receiving') if data.msg_type == 'pic': self.imgs.append(tk.PhotoImage(data=msg)) out_window.image_create(tk.END, image=self.imgs[-1]) out_window.insert(tk.END, '\n') elif data.msg_type == 'text': out_window.insert(tk.END, msg) out_window.yview(tk.END) out_window.config(state=tk.DISABLED) def run_output(self): while True: if self.receive_queue.empty(): break data = self.receive_queue.get() if not data: continue if data.sender not in self.friend_users: self.groups['default'][0].append(data.sender) self.update_groups() self.output_one_message(data) self.update_unread_message() self.root.after(300, self.run_output) def run(self): self.root.withdraw() lg_window = LoginPanel(self.client, self.root) lg_window.run() self.root.deiconify() if self.client.username == None: self.on_closing() return None self.username = self.client.username self.read_groups_data() self.update_groups() for usr in self.friend_users: self.unread_message_num[usr] = 0 self.output = tk.Text(self.frame_chat, state=tk.DISABLED, font=('仿宋', 20)) self.output.place(x=0, y=0, width=630, height=520) self.chat_with_windows[self.username] = self.output self.output.tkraise() self.hello_label.config(text=f'Hello, {self.username}') self.client.run(self.receive_queue) self.root.after(300, self.run_output) self.root.mainloop() def on_closing(self): self.client.stop_signal = True self.client.quit_from_server() for key, val in self.groups.items(): self.groups[key][1] = None self.groups[key][2] = None if self.username: if not file_exist(self.username): os.mkdir(self.username) with open(self.username + '/log.dat', 'wb') as file: pickle.dump(self.groups, file) self.root.quit() try: self.root.destroy() except: pass
def __init__(self, ip, data_port, timeout=5): TCPClient.__init__(self, 'data_client', ip, data_port, timeout=timeout)
from client import TCPClient, ON_MESSAGE, ON_CONNECTED import sys if not (len(sys.argv) == 3 and sys.argv[2].isdigit()): sys.exit(0) client = TCPClient(ip=sys.argv[1], port=int(sys.argv[2])) @client.on(ON_CONNECTED) def on_connected(*args, **kwargs): print(f"Connected to {args}") @client.on(ON_MESSAGE) def on_new_message(*args, **kwargs): print(f"You have new message: {args}") def main(): print("Starting client...") client.start() while True: client.send(input(">>>")) if __name__ == "__main__": main()
from client import TCPClient tc = TCPClient() tc.connect(host="127.0.0.1", port=50123) tc.send("hello") print(tc.receive())
"""Runs the TCP Client sending expressions from file.""" import sys from bcolors import bcolors from client import parse_expression, TCPClient from time import sleep if len(sys.argv) > 1: filepath = sys.argv[1] else: print("USAGE: python TCP-Client.py [input-file]") sys.exit(0) tc = TCPClient(debug=True) tc.connect(host="127.0.0.1", port=50123) # Read file with expressions with open(filepath) as fp: for i, line in enumerate(fp): print("\n-------------") print("{}{}Reading line #{}.{}\n".format(bcolors.WARNING, bcolors.BOLD, i, bcolors.ENDC)) # Remove leading character line = line.replace("\n", "") tc.http_send(file="/", method="POST", params={"expression": line}) response = tc.result() if response is not False: exp = parse_expression(line) print("{}{}The result of {} {} {} is {}{}.".format(
def __init__(self, host, port, buffer_size, imei=""): self.client = TCPClient(host, port, buffer_size) self.imei = imei self.location = Point((0, 0))
from server import TCPServer from client import TCPClient import os from time import sleep if __name__ == "__main__": client = TCPClient('localhost', os.environ.get('PORT')) client.start() # time to create client sleep(1) for i in range(10): data = {'key': 'key'+str(i),'value': 'value'+str(i)} client.sendData(data) sleep(5)
def analysisFile(self, lines): client = TCPClient() for line in lines: client.send(("analysisFile", (line,)), self.analysisFileCallBack)
def registerUser(self): name = self.ui_login.txt_name.text() password = self.ui_login.txt_password.text() TCPClient().send(("addUser", (name, password)))