Skip to content

gh-112020: socketserver: Add an example for keeping the connection open #112054

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 8 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 21 additions & 11 deletions Doc/library/socketserver.rst
Original file line number Diff line number Diff line change
Expand Up @@ -493,11 +493,16 @@ This is the server side::

def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
self.data = self.request.recv(1024)
while self.data:
self.data = self.data.strip()
print("Received from {}:".format(self.client_address[0]))
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
# Receive next message from client. Will return an empty message
# if client has hung up
self.data = self.request.recv(1024)

if __name__ == "__main__":
HOST, PORT = "localhost", 9999
Expand All @@ -516,12 +521,17 @@ objects that simplify communication by providing the standard file interface)::
def handle(self):
# self.rfile is a file-like object created by the handler;
# we can now use e.g. readline() instead of raw recv() calls
self.data = self.rfile.readline().strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# Likewise, self.wfile is a file-like object used to write back
# to the client
self.wfile.write(self.data.upper())
self.data = self.rfile.readline()
while self.data:
self.data = self.data.strip()
print("Received from {}:".format(self.client_address[0]))
print(self.data)
# Likewise, self.wfile is a file-like object used to write back
# to the client
self.wfile.write(self.data.upper())
# Receive next message from client. Will return an empty message
# if client has hung up
self.data = self.rfile.readline()

The difference is that the ``readline()`` call in the second handler will call
``recv()`` multiple times until it encounters a newline character, while the
Expand Down