blob: c887cec6ae3821a812128d9d608cfcf82a853170 [file] [log] [blame]
Guido van Rossum66172522001-04-06 16:32:22 +00001# test asynchat -- requires threading
2
Guido van Rossumdca060c2001-04-06 16:43:49 +00003import asyncore, asynchat, socket, threading, time
Guido van Rossum66172522001-04-06 16:32:22 +00004
5HOST = "127.0.0.1"
6PORT = 54321
7
8class echo_server(threading.Thread):
9
10 def run(self):
11 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
12 sock.bind((HOST, PORT))
13 sock.listen(1)
14 conn, client = sock.accept()
15 buffer = ""
16 while "\n" not in buffer:
17 data = conn.recv(10)
18 if not data:
19 break
20 buffer = buffer + data
21 while buffer:
22 n = conn.send(buffer)
23 buffer = buffer[n:]
24 conn.close()
25 sock.close()
26
27class echo_client(asynchat.async_chat):
28
29 def __init__(self):
30 asynchat.async_chat.__init__(self)
31 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
32 self.connect((HOST, PORT))
33 self.set_terminator("\n")
34 self.buffer = ""
Guido van Rossum66172522001-04-06 16:32:22 +000035
36 def handle_connect(self):
37 print "Connected"
38
39 def collect_incoming_data(self, data):
40 self.buffer = self.buffer + data
41
42 def found_terminator(self):
43 print "Received:", `self.buffer`
44 self.buffer = ""
45 self.close()
46
47def main():
48 s = echo_server()
49 s.start()
Guido van Rossumdca060c2001-04-06 16:43:49 +000050 time.sleep(1) # Give server time to initialize
Guido van Rossum66172522001-04-06 16:32:22 +000051 c = echo_client()
Guido van Rossumdca060c2001-04-06 16:43:49 +000052 c.push("hello ")
53 c.push("world\n")
Guido van Rossum66172522001-04-06 16:32:22 +000054 asyncore.loop()
55
56main()