0

I have created a simple python server that sends back everything it receives.

I wonder if it would be possible to close the connection immediately after sending the data to the client (web browser), and the client then displays the data it has received. Currently, the client displays The connection was reset.

Thanks

#!/user/bin/env python3
import socket

HOST = 'localhost'  # loopback interface address 
PORT = 3000         # non-privileged ports are > 1023

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    while True:
        # connect to the next client in queue
        conn, addr = s.accept()
        with conn:
            print('Connected by', addr)
            data = conn.recv(1024).decode()
            print(data)
            conn.sendall(data.encode())
Chuan
  • 429
  • 5
  • 16

1 Answers1

1

Solution

#!/user/bin/env python3
import socket

HOST = 'localhost'  # loopback interface address 
PORT = 3000         # non-privileged ports are > 1023

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    while True:
        # connect to the next client in queue
        conn, addr = s.accept()
        print('Connected by', addr)
        data = conn.recv(1024).decode()
        print(data)
        conn.sendall(data.encode())
        conn.shutdown(socket.SHUT_WR) # changed

Explanation

The solution uses conn.shutdown(socket.SHUT_WR) which sends a FIN signal instead of conn.close() which sends a RST signal.

We don't want to force the connection to close. TCP setup is expensive, so the browser would ask the server to keep the connection alive to query assets, and in this example the browser asks for style.css.

RST confuses the browser, and Firefox will show you "connection reset" error.

FIN says: "I finished talking to you, but I'll still listen to everything you have to say until you say that you're done."

RST says: "There is no conversation. I won't say anything and I won't listen to anything you say." from FIN vs RST in TCP connections

Here is the Wireshark capture of using shutdown, we see that both the server at 3000 and the browser acknowledged each other's FIN. enter image description here

When using close, we see that enter image description here

A better option would be to wait for the client to initiate the 4 way finalization by programming the server to shut down the socket when the client signals FIN.

The 4 way finalization

enter image description here From https://www.geeksforgeeks.org/tcp-connection-termination/

Chuan
  • 429
  • 5
  • 16