Home > Software engineering >  How to let the server socket react to a second client request?
How to let the server socket react to a second client request?

Time:07-07

I have a simple echo server that echos back whatever it receives. This works well for a single client request.

# echo-server.py

import socket

HOST = "127.0.0.1"  
PORT = 65432 

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print(f"Connected by {addr}")
        while True:
            try:
                data = conn.recv(1024)
            except KeyboardInterrupt:
                print ("KeyboardInterrupt exception captured")
                exit(0)
            conn.sendall(data)


# echo-client.py

import socket

HOST = "127.0.0.1"  # The server's hostname or IP address
PORT = 65432  # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b"Hello, world")
    data = s.recv(1024)

print(f"Received {data!r}")

However, if I finish one client request, and do a second client request, the server no more echoes back. How can I solve this issue?

(base) root@40029e6c3f36:/mnt/pwd# python echo-client.py
Received b'Hello, world'
(base) root@40029e6c3f36:/mnt/pwd# python echo-client.py

CodePudding user response:

On the server side, you need to accept connections in an infinite loop. This should work.

server.py

HOST = "127.0.0.1"  
PORT = 65432 

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    while True:
        conn, addr = s.accept()
        print(f"Connected by {addr}")
        try:
            data = conn.recv(1024)
        except KeyboardInterrupt:
            print ("KeyboardInterrupt exception captured")
            exit(0)
        conn.sendall(data)
  • Related