I am new to socket programming and learning the basics.
This code works fine on one computer. But, when tested using two different computers, it is raising errors related to encoding/decoding.
I've tried different encodings, but none of them worked.
The encodings I've tried and their errors respectively are given below after the code.
I hope someone can help me with it.
Thanks
server.py
import socket
import threading
SERVER="192.168.1.4"
PORT=5051
ADDR=(SERVER, PORT)
SIZE=1024
FORMAT='utf-8'
server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def getfile(conn: socket.socket, addr):
print(f"[NEW CONNECTION] Connected : {conn}")
connected=True
while connected:
fname=conn.recv(SIZE).decode(FORMAT)
if fname=="!disconnect":
connected=False
break
print("[RECV] Receiving the file name")
file=open(fname,"wb")
conn.send("[ACK] Received the file name".encode(FORMAT))
print("Receiving the file data")
data=conn.recv(SIZE)
while data:
file.write(data)
file.flush()
if len(data)<SIZE:
break
data=conn.recv(SIZE)
conn.send("[ACK] Received the data".encode(FORMAT))
file.close()
print(f"[DISCONNECTED] {conn} - disconnected")
conn.close()
def start():
server.listen()
print(f"Server is listening on : {SERVER}")
while True:
conn, addr=server.accept()
threading.Thread(target=getfile, args=(conn, addr)).start()
print(f"[CONNECTIONS] Number of active connections : {threading.active_count()-1}")
print("[STARTING] Server is starting...")
start()
client.py
import socket
import threading
SERVER="192.168.1.4"
PORT=5051
ADDR=(SERVER, PORT)
SIZE=1024
FORMAT='utf-8'
client=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
def send():
file=open("tpic.jpeg","rb")
client.send("nfile.jpeg".encode(FORMAT))
msg=client.recv(SIZE).decode(FORMAT)
print(f"[SERVER] {msg}")
data=file.read(SIZE)
while data:
client.send(data)
if len(data)<SIZE:
break
data=file.read(SIZE)
msg=client.recv(SIZE).decode(FORMAT)
print(f"[SEVRER] {msg}")
file.close()
send()
client.send("!disconnect".encode(FORMAT))
Errors
- FORMAT='utf-8'
Initially,
line 17, in getfile
fname=conn.recv(SIZE).decode(FORMAT)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x95 in position 0: invalid start byte
Now,
line 17, in getfile
fname=conn.recv(SIZE).decode(FORMAT)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf4 in position 1: invalid continuation byte
and
line 17, in getfile
fname=conn.recv(SIZE).decode(FORMAT)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xea in position 0: invalid continuation byte
- FORMAT='utf-16'
line 17, in getfile
fname=conn.recv(SIZE).decode(FORMAT)
UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 12-13: illegal UTF-16 surrogate
- FORMAT='ISO-8859-1'
line 22, in getfile
file=open(fname,"wb")
ValueError: embedded null byte