FareJump
FareJump

Reputation: 113

Python sockets - WinError 10054

I'm trying to make a client and server where the client sends a string to the server and the server sends a response back.

This is the method on my client

def send(self):
    s = socket.socket()
    s.connect(("127.0.0.1", 5012))

    message = bytes("Send!", "utf-8")
    s.send(message)

    data = s.recv(1024)
    data = str(data, "utf-8")

    print(data)

    s.close()   

this is a method in the server which waits for client messages.

   def listener(self):
        print("Startet")
        s = socket.socket()
        s.bind(("127.0.0.1", 5012))
        s.listen(1)
        while True:
            c, addr = s.accept()

            while True:
                data = c.recv(1024)
                data = str(data, "utf-8")

                print(data)

                c.send(bytes("OK", "utf-8"))
            c.close()

Running this I get:

Startet
Send!

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Anaconda3\lib\threading.py", line 914, in _bootstrap_inner
    self.run()
  File "C:\Anaconda3\lib\threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "C:\workspace\Server.py", line 41, in listener
    data = c.recv(1024)
ConnectionAbortedError: [WinError 10053] 
An established connection was disconnected by the software on the hostcomputer

It prints out the Send!, so at least it recieves the messages, but then abruptly stops. The server should be able to run at all times, and take an arbitrary amount of messages from the clients send function.

Upvotes: 0

Views: 6870

Answers (1)

Ton Plooij
Ton Plooij

Reputation: 2641

The client does a send() and then immediately a recv() without checking if data is available (e.g. using accept()). If the socket is non-blocking the recv() immediately returns (or it excepts for some other reason). An empty string is printed and the socket is closed. That's why the server gives an ConnectionAbortedError, the client has already closed the connection. Check this by adding a try/except around the client recv().

Upvotes: 1

Related Questions