Skip to content
Advertisement

I can’t find the error in my socket python program

I was following a socket tutorial and suddenly there was a bug in my code that I couldn’t understand or find

Can anyone help me find the bug? I referenced with the tutorial code and it doesn’t work. The only way is to copy/paste and I don’t like it

this is my server.py file

import socket
import threading
HEADER = 64
FORMAT = 'utf-8'
PORT = 5050
DISCONNECTED_ADDR = "!disCONNECTED"
SERVER = socket.gethostbyname(socket.gethostname())
print(SERVER)
ADDR = (SERVER, PORT)

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)

def handle_client(conn, addr):
    print(f"[NEW CONNECTION] {addr} connected.")

    connected = True
    while connected:
        msg_length = conn.recv(HEADER).decode(FORMAT)
        if msg_length:
            msg_length = int(msg_length)
            msg = conn.recv(msg_length).decode(FORMAT)
            if msg == DISCONNECTED_ADDR:
                connected = False

            print(f"[{addr}] {msg}")
            conn.send("Msg received".encode(FORMAT))

    conn.close()

def main():
    print(f"[LISTENING] Server listening on {SERVER}")
    server.listen()
    while True:
        conn, addr = server.accept()
        thread = threading.Thread(target=handle_client, args=(conn, addr))
        thread.start()
        print("STARTED")


print("APP STARTED")
main()

And this is my client.py file

import socket

HEADER = 64
FORMAT = 'utf-8'
PORT = 5050
DISCONNECTED_ADDR = "!disCONNECTED"

SERVER = "#myipaddress"
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)

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)-1)
    client.send(send_length)
    client.send(message)
    print(client.recv(2048).decode(FORMAT))


send("Hello World!")
input()
send("Hello Everyone!")
input()
send("Hello Tim!")

send(DISCONNECTED_ADDR)

Advertisement

Answer

Can anyone help me find the bug?

    send_length += b' ' * (HEADER - len(send_length)-1)

You miscalculate the padding length of the header in the client. I don’t know why you thought the decrement of 1 were needed – it’s out of place, correct:

    send_length += b' ' * (HEADER - len(send_length))
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement