ctrl x as quit or exit program not working in chat application

Issue

This Content is from Stack Overflow. Question asked by Perseus Uchiha

#codeinServer

import socket
import threading

HOST = ‘127.0.0.1’
PORT = 9090

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))

server.listen()

clients = []
nicknames = []

def broadcast(message):
for client in clients:
client.send(message)

def handle(client):
while True:
try:
message = client.recv(1024)
print(f”{nicknames[clients.index(client)]} says {message}”)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
nicknames.remove(nickname)
break

def receive():
while True:
client, address = server.accept()
print(f”Connected with {str(address)}!”)

    client.send("NICK".encode('utf-8'))
    nickname = client.recv(1024)

    nicknames.append(nickname)
    clients.append(client)

    print(f"Nickname of the client is {nickname}")
    broadcast(f"{nickname} joined the server!n".encode('utf-8'))


    thread = threading.Thread(target=handle, args=(client,))
    thread.start()

print(“Game na”)
receive()

#codeinClient

import socket
import threading
import tkinter
import tkinter.scrolledtext
from tkinter import simpledialog

import keyboard as k
def close():
k.add_hotkey(“ctrl+x”, lambda: quit())

HOST = ‘127.0.0.1’
PORT = 9090

class Client:

def __init__(self, host, port):

    self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.sock.connect((host, port))

    msg = tkinter.Tk()
    msg.withdraw()

    self.nickname = simpledialog.askstring("Enter Name", "Enter a nickname", parent=msg)

    self.gui_done = False
    self.running = True

    gui_thread = threading.Thread(target=self.gui_loop)
    receive_thread = threading.Thread(target=self.receive)

    gui_thread.start()
    receive_thread.start()

def gui_loop(self):
    self.root = tkinter.Tk()
    self.root.configure(bg="lightgray")
    self.root.title('Client-Server ChatApp')

    self.chat_label = tkinter.Label(self.root, text="Chat:", bg="lightgray")
    self.chat_label.config(font=("Arial", 12))
    self.chat_label.pack(padx=20, pady=5)

    self.text_area = tkinter.scrolledtext.ScrolledText(self.root)
    self.text_area.pack(padx=20, pady=5)
    self.text_area.config(state='disabled')

    self.msg_label = tkinter.Label(self.root, text="Message:", bg="lightgray")
    self.msg_label.config(font=("Arial", 12))
    self.msg_label.pack(padx=20, pady=5)

    self.input_area = tkinter.Text(self.root, height=5)
    self.input_area.pack(padx=20, pady=5)

    self.send_button = tkinter.Button(self.root, text="Send", command=self.write)
    self.send_button.config(font=("Arial", 12))
    self.send_button.config(activebackground=("gray"))
    self.send_button.pack(padx=20, pady=5)

    self.gui_done = True

    self.root.protocol("WM_DELETE_WINDOW", self.stop)

    self.root.mainloop()

def write(self):
    message = f"{self.nickname}: {self.input_area.get('1.0', 'end')}"
    self.sock.send(message.encode('utf-8'))
    self.input_area.delete('1.0', 'end')

def stop(self):
    self.running = False
    self.root.destroy()
    self.sock.close()
    exit(0)

def receive(self):
    while self.running:
        try:
            message = self.sock.recv(1024).decode('utf-8')
            if message == 'NICK':
                self.sock.send(self.nickname.encode('utf-8'))
            else:
                if self.gui_done:
                    self.text_area.config(state='normal')
                    self.text_area.insert('end', message)
                    self.text_area.yview('end')
                    self.text_area.config(state='disabled')
        except ConnectionAbortedError:
            break
        except:
            print("Error")
            self.sock.close()
            break

    def exit_app(e):
        self.root.destroy()

    self.root.bind('<Control-x>', exit_app)
    self.root.mainloop()

client = Client(HOST, PORT)


Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?

Exit mobile version