[Python] Why does my server socket not receive data?

Discussão em 'Python' iniciado por Stack, Janeiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    I have some problems with socket programming. I started learning this topic and created a small echo server/client application from the tutorial, after that I created a multithreaded version of it for multiple clients. It works fine with the following code:

    Server:

    from Rest_Endpoint.thread import ConnectionThread

    HOST = ''
    PORT = 6000

    def start_server():
    server: socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
    server.bind((HOST,PORT))
    server.listen(10)
    print('listen to port', PORT)
    server.setblocking(False)

    while True:
    try:
    conn, addr = server.accept() # Will throw BlockingIOError if no connections
    print('Connected by:', addr)
    thread_spawn(conn, addr)
    except BlockingIOError:
    # No incoming connection; continue the loop
    continue
    except Exception as e:
    print(f'Unexpected error: {e}')
    break

    def thread_spawn(conn, addr):
    print('spawn new connection thread')
    ConnectionThread(conn=conn, addr=addr).run()

    def main():
    start_server()


    if __name__ == '__main__':
    main()


    Spawned thread:

    import threading

    class ConnectionThread(threading.Thread):
    def __init__(self,conn,addr, **kwargs) -> None:
    self.conn = conn
    self.addr = addr
    super().__init__()

    def handle_data(self):
    print('Connected by', self.addr)
    while True:
    print(f' waiting for message {self.__repr__()}')
    data = self.conn.recv(1024)

    if data:
    print('prints data: ')
    print(data)
    self.conn.sendall(data)

    def run(self) -> None:
    self.handle_data()


    Client:

    # Echo client program
    import socket

    HOST = '' # The remote host
    PORT = 6000 # The same port as used by the server
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    try:
    # Connect to the server
    s.connect((HOST, PORT))
    print(f'Connected to server at {HOST}:{PORT}')

    while True:
    # message = input()
    # bmessage = (message + '\n').encode('utf-8')
    s.sendall(b'test')
    # print(bmessage)'

    except ConnectionRefusedError:
    print(f"Could not connect to server at {HOST}:{PORT}. Ensure the server is running.")
    except Exception as e:
    print(f"An error occurred: {e}")


    When I start the client program, I get this:

    Connected by ('127.0.0.1', 51804)
    waiting for message <ConnectionThread(Thread-1, initial)>
    prints data:
    b'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest'


    I understand, that tcp is a stream and because of the while True Loop I do get this result of multiple test in a row.

    But when I try to switch the client code to:

    while True:
    message = input()
    bmessage = (message).encode('utf-8')
    s.sendall(b'test')
    print(bmessage)


    I don't receive any message at the server side and I do not understand why. It connects, but I do not get any data.

    Maybe someone can help me with an explanation.

    This client code does not work:

    # Echo client program
    import socket

    HOST = '' # The remote host
    PORT = 6000 # The same port as used by the server
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    try:
    # Connect to the server
    s.connect((HOST, PORT))
    print(f'Connected to server at {HOST}:{PORT}')

    while True:
    message = input()
    bmessage = (message).encode('utf-8')
    s.sendall(b'test')
    print(bmessage)

    except ConnectionRefusedError:
    print(f"Could not connect to server at {HOST}:{PORT}. Ensure the server is running.")
    except Exception as e:
    print(f"An error occurred: {e}")

    Continue reading...

Compartilhe esta Página