Форум сайта python.su
Всем привет, нашел простенький чат мэссенджер по локалке, сделал ему графический интерфейс на tkinter, он работает только по локалке, кто подскажет можно ли его загрузить на хостинг, чтобы мы с друзьями из разных городом могли через него переписываться.
Вот код самого сервера:
from socket import AF_INET, socket, SOCK_STREAM from threading import Thread def accept_incoming_connections(): """Sets up handling for incoming clients.""" while True: client, client_address = SERVER.accept() print("%s:%s подключился к чату" % client_address) client.send(bytes("Введи свой никнейм и нажми Enter", "utf8")) addresses[client] = client_address Thread(target=handle_client, args=(client,)).start() def handle_client(client): # Takes client socket as argument. """Handles a single client connection.""" name = client.recv(BUFSIZ).decode("utf8") welcome = 'Привет %s! Если захочешь выйти из чата, введи {quit}' % name client.send(bytes(welcome, "utf8")) msg = "%s зашел в чат!" % name broadcast(bytes(msg, "utf8")) clients[client] = name while True: msg = client.recv(BUFSIZ) if msg != bytes("{quit}", "utf8"): broadcast(msg, name+": ") else: client.send(bytes("{quit}", "utf8")) client.close() del clients[client] broadcast(bytes("%s вышел из чата" % name, "utf8")) break def broadcast(msg, prefix=""): # prefix is for name identification. """Broadcasts a message to all the clients.""" for sock in clients: sock.send(bytes(prefix, "utf8")+msg) clients = {} addresses = {} HOST = '' PORT = 33000 BUFSIZ = 1024 ADDR = (HOST, PORT) SERVER = socket(AF_INET, SOCK_STREAM) SERVER.bind(ADDR) if __name__ == "__main__": SERVER.listen(5) print("Жду подключения пользователей...") ACCEPT_THREAD = Thread(target=accept_incoming_connections) ACCEPT_THREAD.start() ACCEPT_THREAD.join() SERVER.close()
from socket import AF_INET, socket, SOCK_STREAM from threading import Thread import tkinter def receive(): """Handles receiving of messages.""" while True: try: msg = client_socket.recv(BUFSIZ).decode("utf8") msg_list.insert(tkinter.END, msg) except OSError: # Possibly client has left the chat. break def send(event=None): """Handles sending of messages.""" msg = my_msg.get() my_msg.set("") client_socket.send(bytes(msg, "utf8")) if msg == "{quit}": client_socket.close() top.quit() def on_closing(event=None): my_msg.set("{quit}") send() top = tkinter.Tk() top.title("Messanger by Fade") top.resizable( width = False, height = False) top.geometry( '600x400' ) #размер окна top['bg'] = '#3d3d42' #задний фон messages_frame = tkinter.Frame(top) my_msg = tkinter.StringVar() # For the messages to be sent. my_msg.set("") scrollbar = tkinter.Scrollbar(messages_frame) msg_list = tkinter.Listbox(messages_frame, height=15, width=100, yscrollcommand=scrollbar.set, bg = '#3d3d42', fg = 'yellow', font = 'Consolas 12') 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, font = 'Consolas 12', relief='solid', justify='center', width='50', bd='2', bg='#515154', fg='#73a87d' ) entry_field.bind("<Return>", send) entry_field.pack( pady = 5 ) send_button = tkinter.Button(top, command=send, text = 'Отправить', font = 'Consolas 12', width ='16', bg='#515154', fg='yellow', relief='solid', justify='center', activebackground='gray', activeforeground='#05ff69') send_button.pack( pady = 5 ) top.protocol("WM_DELETE_WINDOW", on_closing) #----Now comes the sockets part---- HOST = '192.168.0.10' #мой локальный ip adress PORT = 33000 if not PORT: PORT = 33000 else: PORT = int(PORT) BUFSIZ = 1024 ADDR = (HOST, PORT) client_socket = socket(AF_INET, SOCK_STREAM) client_socket.connect(ADDR) receive_thread = Thread(target=receive) receive_thread.start() tkinter.mainloop()
Офлайн