I have created a messaging application using python socket programming and I have enabled two separate devices connected to the ip address to exchange messages, I have no problem in this regard. I tried to add a file sending button and function to this application but I couldn’t succeed, all it can do is read the contents of the txt extension files, when I try to send jpg or jpeg type files, it does not give an error and produces different texts (I think it reads the image file) can you help me?
client.py:
import socket
import threading
import tkinter
from tkinter import filedialog
import os
def receive():
"""Gelen mesajları işler."""
while True:
try:
msg = client_socket.recv(1024)
if msg.startswith(b"{dosya_bilgisi}"):
dosya_bilgisi = msg.decode("utf-8").split("{dosya_bilgisi}")[1]
dosya_adi, dosya_boyutu = dosya_bilgisi.split(" ")
dosya_boyutu = int(dosya_boyutu)
download_file(dosya_adi, dosya_boyutu)
else:
msg_list.insert(tkinter.END, msg)
except OSError:
break
def download_file(dosya_adi, dosya_boyutu):
file_path = filedialog.asksaveasfilename(initialdir="/", title="Dosyayı kaydet", initialfile=dosya_adi, filetypes=(("All files", "*.*"),))
if file_path:
with open(file_path, "wb") as file:
received_size = 0
while received_size < dosya_boyutu:
data = client_socket.recv(BUFSIZ)
file.write(data)
received_size += len(data)
msg_list.insert(tkinter.END, "Dosya {} kaydedildi.".format(dosya_adi))
def send(event=None):
msg = my_msg.get()
my_msg.set("")
if msg.startswith("dosya_gonder"):
file_path = msg.split(" ")[1]
if os.path.isfile(file_path):
file_name = os.path.basename(file_path)
file_size = os.path.getsize(file_path)
client_socket.send(bytes("dosya_bilgisi{} {}".format(file_name, file_size), "utf8"))
send_file(file_path)
else:
msg_list.insert(tkinter.END, "Dosya bulunamadı!")
else:
client_socket.send(bytes(msg, "utf8"))
if msg == "{quit}":
client_socket.close()
top.quit()
def on_send_file_button_click():
file_path = filedialog.askopenfilename()
if file_path:
my_msg.set("dosya_gonder " + file_path)
send()
def on_closing(event=None):
"""Pencere kapatıldığında çağrılır."""
my_msg.set("{quit}")
send()
def send_file(file_path):
with open(file_path, "rb") as file:
file_data = file.read() # Dosya içeriğini oku
file_size = len(file_data) # Dosya boyutunu al
# Dosya boyutunu sunucuya gönder
client_socket.sendall(f"{file_size:<10}".encode())
# Dosya verisini sunucuya gönder
client_socket.sendall(file_data)
msg_list.insert(tkinter.END, f"{file_path} dosyası gönderildi.")
top = tkinter.Tk()
top.title("Sohbet Uygulaması")
messages_frame = tkinter.Frame(top)
my_msg = tkinter.StringVar() # Gönderilecek mesaj
my_msg.set("")
scrollbar = tkinter.Scrollbar(messages_frame) # Önceki mesajları görmek için
msg_list = tkinter.Listbox(messages_frame, height=15, width=50, yscrollcommand=scrollbar.set)
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)
entry_field.bind("<Return>", send)
entry_field.pack()
send_button_frame = tkinter.Frame(top)
send_button_frame.pack()
send_button = tkinter.Button(send_button_frame, text="Gönder", command=send)
send_button.pack(side=tkinter.LEFT)
send_file_button = tkinter.Button(send_button_frame, text="Dosya Gönder", command=on_send_file_button_click)
send_file_button.pack(side=tkinter.LEFT)
top.protocol("WM_DELETE_WINDOW", on_closing)
HOST = input('Sunucu adresini girin: ') # Sunucunun adresini girin
PORT = 3300
BUFSIZ = 1024
ADDR = (HOST, PORT)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client_socket.connect(ADDR)
print("Sunucuya başarıyla bağlanıldı.")
except Exception as e:
print("Sunucuya bağlanılamadı:", e)
exit()
receive_thread = threading.Thread(target=receive)
receive_thread.start()
tkinter.mainloop() # GUI arayüzünü başlat
server.py:
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import os
def gelen_baglantilari_kabul_et():
"""Gelen istemcilerin işlenmesini ayarlar."""
while True:
istemci, istemci_adresi = SUNUCU.accept()
print("%s:%s bağlandı." % istemci_adresi)
istemci.send(bytes("Sohbete hoş geldiniz! Sohbete başlayabilmek için bir kullanıcı adı seçin.", "utf8"))
adresler[istemci] = istemci_adresi
Thread(target=istemciyi_isle, args=(istemci,)).start()
def istemciyi_isle(istemci):
"""Tek bir istemci bağlantısını işler."""
isim = istemci.recv(BUFSIZ).decode("utf8")
hosgeldin_mesaji = 'Merhaba %s! Sohbetten ayrılmak için, metin kutusuna {quit} komutunu yazabilirsiniz.' % isim
istemci.send(bytes(hosgeldin_mesaji, "utf8"))
mesaj = "%s sohbete katıldı!" % isim
herkese_gonder(bytes(mesaj, "utf8"))
istemciler[istemci] = isim
while True:
msg = istemci.recv(BUFSIZ)
if msg != bytes("{quit}", "utf8"):
if msg.startswith(b"{dosya_boyutu}"):
dosya_bilgisi = msg.decode("utf8").split("{dosya_boyutu}")[1]
dosya_adi, dosya_boyutu = dosya_bilgisi.split(" ")
dosya_boyutu = int(dosya_boyutu)
dosya_al(istemci, dosya_adi, dosya_boyutu)
else:
herkese_gonder(msg, isim+": ")
else:
istemci.send(bytes("{quit}", "utf8"))
istemci.close()
del istemciler[istemci]
herkese_gonder(bytes("%s sohbetten ayrıldı." % isim, "utf8"))
break
"""Tek bir istemci bağlantısını işler."""
isim = istemci.recv(BUFSIZ).decode("utf8")
hosgeldin_mesaji = 'Merhaba %s! Sohbetten ayrılmak için, metin kutusuna {quit} komutunu yazabilirsiniz.' % isim
istemci.send(bytes(hosgeldin_mesaji, "utf8"))
mesaj = "%s sohbete katıldı!" % isim
herkese_gonder(bytes(mesaj, "utf8"))
istemciler[istemci] = isim
while True:
msg = istemci.recv(BUFSIZ)
if msg != bytes("{quit}", "utf8"):
if msg.startswith(b"{dosya_boyutu}"):
dosya_bilgisi = msg.decode("utf8").split("{dosya_boyutu}")[1]
dosya_adi, dosya_boyutu = dosya_bilgisi.split(" ")
dosya_boyutu = int(dosya_boyutu)
dosya_al(istemci, dosya_adi, dosya_boyutu)
else:
herkese_gonder(msg, isim+": ")
else:
istemci.send(bytes("{quit}", "utf8"))
istemci.close()
del istemciler[istemci]
herkese_gonder(bytes("%s sohbetten ayrıldı." % isim, "utf8"))
break
def herkese_gonder(msg, prefix=""):
"""Tüm istemcilere bir mesajı yayınlar."""
for sock in istemciler:
sock.send(bytes(prefix, "utf8")+msg)
def dosya_al(istemci, dosya_adi, dosya_boyutu):
with open(dosya_adi, "wb") as dosya:
alinan_boyut = 0
while alinan_boyut < dosya_boyutu:
data = istemci.recv(BUFSIZ)
dosya.write(data)
alinan_boyut += len(data)
istemci.send(bytes("Dosya {} alındı.".format(dosya_adi), "utf8"))
# Sunucudan onay mesajı al
onay_mesaji = istemci.recv(BUFSIZ).decode("utf8")
print(onay_mesaji)
istemciler = {}
adresler = {}
HOST = 'localhost'
PORT = 3300
BUFSIZ = 1024
ADDR = (HOST, PORT)
SUNUCU = socket(AF_INET, SOCK_STREAM)
SUNUCU.bind(ADDR)
if __name__ == "__main__":
SUNUCU.listen(5)
print("Bağlantı bekleniyor...")
KABUL_THREAD = Thread(target=gelen_baglantilari_kabul_et)
KABUL_THREAD.start()
KABUL_THREAD.join()
SUNUCU.close()
I have done research from different sources and watched videos, but I could not succeed, the only thing I can do on behalf of the file for now is to read the contents of the txt file.