0

I'm trying to run a python socket server on my local network, with this server code:

import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((socket.gethostname(), 9876))
serversocket.listen(5)
while True:
    c, addr = serversocket.accept()
    while True:
        data = c.recv(1024).decode()
        print(data)
        c.send(data.encode())

Then, using netcat on another network machine, I can connect to the server and send text in, and have it mirrored back. However, after about two or three tries, it suddenly drops back out to the command line and no longer accepts any connections. The server side, however acts the same, and appears like it didn't see the last incoming message.

If I try to connect to it with another socket, it does the same thing, but instead throws error 104, and then error 32.

I am completely stumped. I've tried adding threads, and everything else that I can think of. If anyone on has any ideas on why this is happening, or ways to work around it, I'd love to hear. Thanks! I'm using python 3.5.

Thanks!

Conrad
  • 239
  • 2
  • 8
  • The server only accepts one connection. The socket accept part isn't in a loop. – Barmar Sep 25 '19 at 23:10
  • The inner loop never ends, so you'll never repeat the outer loop. – Barmar Sep 25 '19 at 23:17
  • You should detect EOF and break out of the inner loop. – Barmar Sep 25 '19 at 23:19
  • If you kill the server and try to start it again soon, you need to use the `SO_REUSEADDR` socket option to bind to the same port. See https://stackoverflow.com/questions/5875177/how-to-close-a-socket-left-open-by-a-killed-program – Barmar Sep 25 '19 at 23:21

0 Answers0