Because your CGI program is basically an "execute once"
type program, your server needs to behave apropriately.
There is no point in your server keeping the connection open
because once the client (.cgi program) has completed it will
close the socket from its end. If what you want to do
is have the .cgi program be able to send multiple requests
to the server in one "session" (i.e. one user "submit" from
the webpage) you should do something like have the
.cgi send a "logoff" message to the server which causes it to
tidy things up and flush the connection from its end.
Beware that the kind of think you're writing is fraught with
danger and could cause lots of problems if someone ever hacked
the protocol (not hard to do) unless you have authentication
and encryption built into the client/server protocol.