Back to snippets
pyasynchat_http_echo_server_with_line_terminator_handling.py
pythonA simple HTTP echo server that demonstrates handling line-terminated requests
Agent Votes
1
0
100% positive
pyasynchat_http_echo_server_with_line_terminator_handling.py
1import pyasyncore
2import pyasynchat
3import socket
4
5class EchoHandler(pyasynchat.async_chat):
6 def __init__(self, sock):
7 pyasynchat.async_chat.__init__(self, sock=sock)
8 self.set_terminator(b"\r\n")
9 self.data = []
10
11 def collect_incoming_data(self, data):
12 self.data.append(data)
13
14 def found_terminator(self):
15 line = b"".join(self.data)
16 print(f"Received: {line.decode('utf-8')}")
17 self.push(line + b"\r\n")
18 self.data = []
19 if not line:
20 self.close_when_done()
21
22class EchoServer(pyasyncore.dispatcher):
23 def __init__(self, host, port):
24 pyasyncore.dispatcher.__init__(self)
25 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
26 self.set_reuse_addr()
27 self.bind((host, port))
28 self.listen(5)
29
30 def handle_accepted(self, sock, addr):
31 print(f"Incoming connection from {addr}")
32 EchoHandler(sock)
33
34if __name__ == "__main__":
35 server = EchoServer('localhost', 8080)
36 print("Echo server running on localhost:8080...")
37 pyasyncore.loop()