Reputation: 112
So lets say I have a server.py and a client.py with the following code:
server.py
import socket
def listen():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 5555
s.bind((host, port))
s.listen(128)
print("LISTENING FOR INCOMING CONNECTIONS")
c, addr = s.accept()
print("GOT CONNECTION FROM", addr)
while True:
data = c.recv(1024)
data = data.decode("utf-8")
data = data.upper()
c.send(data.encode("utf-8"))
listen()
and client.py
import socket
def connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 5555
s.connect((host, port))
print("CONNECTED TO HOST")
while True:
command = input("command> ")
s.send(command.encode("utf-8"))
data = s.recv(1024)
print(str(data.decode("utf-8")))
connect()
And now if I disconnect the client and try to reconnect to the server it won't work. (and by will not work I mean the connection won't get established)
Upvotes: 1
Views: 679
Reputation: 948
In your listen
function in server.py
, you are only calling the accept
function once. accept
must be called for each client connection you want to accept. To resolve your problem, you can just put the latter part of the function in a loop:
def listen():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 5555
s.bind((host, port))
s.listen(128)
while True:
print("Waiting for an incoming connection...")
c, addr = s.accept()
print("GOT CONNECTION FROM", addr)
# Serve the connection
try:
while True:
data = c.recv(1024)
if len(data) == 0:
print("Client closed connection")
break
data = data.decode("utf-8")
data = data.upper()
c.send(data.encode("utf-8"))
except Exception as e:
print("Connection died: {}".format(e))
This will mean that only 1 client can be connected at a time.
Instead of writing this type of code yourself, I'd highly recommend taking a look at SocketServer in the Python standard library. This library takes care of the boilerplate listen/accept stuff and also has some advanced features that lets you easily handle more than one client connection at the same time (if you need that)
https://docs.python.org/3/library/socketserver.html#socketserver-tcpserver-example
Upvotes: 1