То, что я пытался сделать.
import socket, select, sys from tkinter import * def prompt(name) : log.insert(END, '<You> ') host = 'localhost' port = 5000 tk = Tk() text = StringVar() name = StringVar() name.set('User') text.set('') tk.title('MegaChat') tk.geometry('400x300') log = Text(tk) nick = Entry(tk, textvariable=name) msg = Entry(tk, textvariable=text) msg.pack(side='bottom', fill='x', expand='true') nick.pack(side='bottom', fill='x', expand='true') log.pack(side='top', fill='both',expand='true') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(2) # connect to remote host try : s.connect((host, port)) except : log.insert(END, 'Unable to connect\n') #sys.exit() log.insert(END, 'Connected to remote host. Start sending messages') while 1: socket_list = [s] # Get the list sockets which are readable read_sockets, write_sockets, error_sockets = select.select(socket_list , [], []) for sock in read_sockets: #incoming message from remote server if sock == s: data = sock.recv(4096).decode() if not data : log.insert(END, '\nDisconnected from chat server') #sys.exit() else : #print data prompt() log.insert(END, data) #user entered a message else: s.send(text.encode()) #prompt() #вот сюда он не доходит из-за бесконечного цикла выше tk.mainloop()
Рабочая версия на консольке
import socket, select, string, sys def prompt() : sys.stdout.write('<You> ') sys.stdout.flush() #main function if __name__ == "__main__": host = 'localhost' port = 5000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(2) # connect to remote host try : s.connect((host, port)) except : print('Unable to connect') sys.exit() print('Connected to remote host. Start sending messages') prompt() while 1: socket_list = [sys.stdin, s] # Get the list sockets which are readable read_sockets, write_sockets, error_sockets = select.select(socket_list , [], []) for sock in read_sockets: #incoming message from remote server if sock == s: data = sock.recv(4096).decode() if not data : print('\nDisconnected from chat server') sys.exit() else : #print data sys.stdout.write(data) prompt() #user entered a message else : msg = sys.stdin.readline() s.send(msg.encode()) prompt()