error I got while making python voice speech application

I wrote a voice chat application code, but when we run this code and join a voice channel, I get the errors in the photo

error1
error2

here is my codes;
client code:

import tkinter as tk
from tkinter import messagebox
import pyaudio
import socket
import threading
import time

HOST = '127.0.0.1'
PORT = 65432


class VoiceChatApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Voice Chat Application")
        self.username = ""
        self.channel = None
        self.is_mic_on = True

        self.setup_gui()
        self.p = pyaudio.PyAudio()
        self.stream = None
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect_to_server()
        threading.Thread(target=self.receive_data, daemon=True).start()

    def setup_gui(self):
        self.root.geometry("300x400")
        self.root.configure(bg="#2e2e2e")

        # Title label
        tk.Label(self.root, text="Voice Chat", font=("Helvetica", 16, "bold"), fg="#ffffff", bg="#2e2e2e").pack(pady=10)

        # Username entry
        self.username_entry = tk.Entry(self.root, font=("Helvetica", 12), bg="#ffffff", fg="#000000")
        self.username_entry.insert(0, "Enter username")
        self.username_entry.pack(pady=5, padx=10, fill=tk.X)

        # Set Username button
        tk.Button(self.root, text="Set Username", command=self.set_username, font=("Helvetica", 12), bg="#4CAF50",
                  fg="#ffffff", relief=tk.RAISED).pack(pady=5, padx=10, fill=tk.X)

        # Channel selection
        self.channel_var = tk.StringVar(value="Select Channel")
        self.channel_menu = tk.OptionMenu(self.root, self.channel_var, "Channel1", "Channel2")
        self.channel_menu.config(font=("Helvetica", 12), bg="#ffffff", fg="#000000")
        self.channel_menu.pack(pady=5, padx=10, fill=tk.X)

        # Join Channel button
        tk.Button(self.root, text="Join Channel", command=self.join_channel, font=("Helvetica", 12), bg="#2196F3",
                  fg="#ffffff", relief=tk.RAISED).pack(pady=5, padx=10, fill=tk.X)

        # Leave Channel button
        tk.Button(self.root, text="Leave Channel", command=self.leave_channel, font=("Helvetica", 12), bg="#FFC107",
                  fg="#ffffff", relief=tk.RAISED).pack(pady=5, padx=10, fill=tk.X)

        # Current Channel label
        self.current_channel_label = tk.Label(self.root, text="Current Channel: None", font=("Helvetica", 12),
                                              fg="#ffffff", bg="#2e2e2e")
        self.current_channel_label.pack(pady=5)

        # Mute button
        self.mute_button = tk.Button(self.root, text="Mute Microphone", command=self.toggle_mic, font=("Helvetica", 12),
                                     bg="#F44336", fg="#ffffff", relief=tk.RAISED)
        self.mute_button.pack(pady=5, padx=10, fill=tk.X)

        # User list
        self.user_list_label = tk.Label(self.root, text="Users in Channel:", font=("Helvetica", 12), fg="#ffffff",
                                        bg="#2e2e2e")
        self.user_list_label.pack(pady=5)
        self.user_listbox = tk.Listbox(self.root, font=("Helvetica", 12), bg="#ffffff", fg="#000000")
        self.user_listbox.pack(pady=5, padx=10, fill=tk.BOTH, expand=True)

        # Exit button
        tk.Button(self.root, text="Exit Application", command=self.exit_application, font=("Helvetica", 12),
                  bg="#F44336", fg="#ffffff", relief=tk.RAISED).pack(pady=5, padx=10, fill=tk.X)

    def connect_to_server(self):
        while True:
            try:
                self.socket.connect((HOST, PORT))
                break
            except Exception as e:
                print(f"Connection attempt failed: {e}")
                time.sleep(5)

    def set_username(self):
        self.username = self.username_entry.get()
        if not self.username:
            messagebox.showwarning("Warning", "Username cannot be empty")
        else:
            messagebox.showinfo("Info", f"Username set to {self.username}")

    def join_channel(self):
        self.channel = self.channel_var.get()
        if self.channel in ["Channel1", "Channel2"]:
            message = f"JOIN|{self.channel}|{self.username}"
            try:
                self.socket.send(message.encode())
                self.start_audio_stream()
                self.current_channel_label.config(text=f"Current Channel: {self.channel}")
            except Exception as e:
                messagebox.showerror("Connection Error", f"Unable to send message to server: {e}")
        else:
            messagebox.showwarning("Warning", "Please select a valid channel")

    def leave_channel(self):
        if self.channel:
            message = f"LEAVE|{self.channel}|{self.username}"
            try:
                self.socket.send(message.encode())
                self.stop_audio_stream()
                self.current_channel_label.config(text="Current Channel: None")
                self.channel = None
            except Exception as e:
                messagebox.showerror("Connection Error", f"Unable to send message to server: {e}")
        else:
            messagebox.showwarning("Warning", "You are not in a channel")

    def start_audio_stream(self):
        try:
            device_index = None
            for i in range(self.p.get_device_count()):
                info = self.p.get_device_info_by_index(i)
                if info['maxInputChannels'] > 0:
                    device_index = i
                    break

            if device_index is None:
                raise ValueError("No input device found")

            self.stream = self.p.open(format=pyaudio.paInt16,
                                      channels=1,
                                      rate=44100,
                                      input=True,
                                      input_device_index=device_index,
                                      frames_per_buffer=1024,
                                      stream_callback=self.audio_callback)
        except Exception as e:
            messagebox.showerror("Audio Error", f"Unable to start audio stream: {e}")

    def audio_callback(self, in_data, frame_count, time_info, status):
        if self.is_mic_on:
            try:
                self.socket.sendall(in_data)
            except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError) as e:
                print(f"Audio send error: {e}")
                self.stop_audio_stream()

                messagebox.showerror("Connection Error", "Connection lost while sending audio data")
        return (None, pyaudio.paContinue)

    def stop_audio_stream(self):
        if self.stream:
            try:
                self.stream.stop_stream()
                self.stream.close()
            except IOError as e:
                print(f"Stream stop error: {e}")
            self.stream = None

    def toggle_mic(self):
        self.is_mic_on = not self.is_mic_on
        status = "Muted" if not self.is_mic_on else "Unmuted"
        self.mute_button.config(text=f"Microphone {status}")

    def receive_data(self):
        while True:
            try:
                message = self.socket.recv(1024).decode()
                if message.startswith("UPDATE"):
                    _, channel, users = message.split('|', 2)
                    self.user_listbox.delete(0, tk.END)
                    for user in users.split(', '):
                        self.user_listbox.insert(tk.END, user)
            except (ConnectionResetError, ConnectionAbortedError) as e:
                print(f"Receive data error: {e}")
                self.connect_to_server()
            except Exception as e:
                print(f"Unexpected error: {e}")

    def exit_application(self):
        if self.stream:
            self.stop_audio_stream()
        self.socket.close()
        self.root.destroy()


if __name__ == "__main__":
    root = tk.Tk()
    app = VoiceChatApp(root)
    root.mainloop()

server code:

import socket
import threading


HOST = '127.0.0.1'
PORT = 65432


channels = {"Channel1": [], "Channel2": []}
connections = []

def handle_client(conn, addr):
    print(f"Yeni bağlantı: {addr}")
    try:
        while True:
            message = conn.recv(1024).decode()
            if not message:
                break
            command = message.split('|')
            if command[0] == "JOIN":
                channel = command[1]
                username = command[2]
                if channel in channels:
                    channels[channel].append(username)
                    update_users_in_channel(channel)
            elif command[0] == "LEAVE":
                channel = command[1]
                username = command[2]
                if channel in channels and username in channels[channel]:
                    channels[channel].remove(username)
                    update_users_in_channel(channel)

    except (ConnectionResetError, ConnectionAbortedError) as e:
        print(f"Connection error: {e}")
    finally:
        conn.close()
        connections.remove(conn)
        print(f"Bağlantı kapandı: {addr}")

def update_users_in_channel(channel):
    user_list = ', '.join(channels[channel])
    message = f"UPDATE|{channel}|{user_list}"
    for conn in connections:
        try:
            conn.send(message.encode())
        except (BrokenPipeError, ConnectionResetError) as e:
            print(f"Broadcast error: {e}")
            connections.remove(conn)

def start_server():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((HOST, PORT))
    server_socket.listen()
    print("Sunucu başlatıldı ve dinleniyor...")

    while True:
        conn, addr = server_socket.accept()
        connections.append(conn)
        threading.Thread(target=handle_client, args=(conn, addr), daemon=True).start()

if __name__ == "__main__":
    start_server()

I can’t understand what’s wrong

I would be very grateful if you could help me.

I’m trying to improve myself by making a discord replica with a simple interface. i also got help from chatgpt while writing the code. but he couldn’t find a solution to this error i got.

New contributor

Osman Teksoy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật