This is my server script to recieve and send messages to all clients
import socket
import threading
HEADER = 64
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
clients = set()
clients_lock = threading.Lock()
def handle_client(conn, addr):
name = conn.recv(HEADER).decode(FORMAT)
if name:
name = int(name)
msg_name = conn.recv(name).decode(FORMAT)
print(f"[NEW CONNECTION] {msg_name} connected.")
connection_message = f"{msg_name} connected."
with clients_lock:
for c in clients:
if c != conn:
message = connection_message.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
c.sendall(send_length)
c.sendall(message)
with clients_lock:
clients.add(conn)
connected = True
try:
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg1 = conn.recv(msg_length).decode(FORMAT)
msg = f"{msg_name}: {msg1}"
if msg1 == DISCONNECT_MESSAGE:
connected = False
print(f"{msg}")
with clients_lock:
for c in clients:
if c != conn:
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
c.sendall(send_length)
c.sendall(message)
msg = f"You: {msg1}"
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
conn.send(send_length)
conn.send(message)
finally:
with clients_lock:
clients.remove(conn)
conn.close()
def start():
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.daemon = True
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print("[STARTING] server is starting...")
start()
The problem is, if a server disconnects without sending the DISCONNECT_MESSAGE, i.e. I forcefully closed the program before it finishes, I get Brokenpipe error.
This is the client script:
import socket
import threading
import tkinter as tk
def returnname():
def receiving():
receiving = True
while receiving:
msg_length = client.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = client.recv(msg_length).decode(FORMAT)
TEXTAREA.insert("end", msg)
TEXTAREA.see("end")
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
def sendmessage():
mess = MESSAGEFIELD.get()
MESSAGEFIELD.delete(0, "end")
send(mess)
def quitmessage():
send(DISCONNECT_MESSAGE)
exit()
name = FIELD.get()
FIELD.pack_forget()
BUTTON.pack_forget()
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
message = name.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
thread = threading.Thread(target=receiving)
thread.daemon = True
thread.start()
MESSAGEFIELD = tk.Entry(TOP)
SENDBUTTON = tk.Button(TOP, text="Send", command=sendmessage)
QUITBUTTON = tk.Button(TOP, text="Quit", command=quitmessage)
TEXTAREA = tk.Listbox(TOP)
SCROLLBAR = tk.Scrollbar(TOP)
MESSAGEFIELD.pack()
SENDBUTTON.pack()
QUITBUTTON.pack()
TEXTAREA.pack(side="left", expand=True, fill="both")
SCROLLBAR.pack(side="right", fill="both")
SCROLLBAR.config(command=TEXTAREA.yview)
HEADER = 64
PORT = 5050
FORMAT = 'utf-8'
SERVER = "IP ADDRESS OF SERVER"
ADDR = (SERVER, PORT)
DISCONNECT_MESSAGE = "!DISCONNECT"
TOP = tk.Tk()
FIELD = tk.Entry(TOP)
FIELD.insert(0, "Enter Name Here")
BUTTON = tk.Button(TOP, text="Send", command=returnname)
FIELD.pack(expand=True)
BUTTON.pack(expand=True)
TOP.mainloop()
Can anyone tell me if there is any way I can fix this issue?
Sorry if my explanation of the problem was bad. I am bad at explaining stuff.