blob: 60017e0ab53d9d8c66723870c5ac380c1894b543 [file] [log] [blame]
Guido van Rossum66172522001-04-06 16:32:22 +00001# test asynchat -- requires threading
2
Guido van Rossum9df3eab2001-04-14 14:35:43 +00003import thread # If this fails, we can't test this module
Guido van Rossumdca060c2001-04-06 16:43:49 +00004import asyncore, asynchat, socket, threading, time
Guido van Rossum66172522001-04-06 16:32:22 +00005
6HOST = "127.0.0.1"
7PORT = 54321
8
9class echo_server(threading.Thread):
10
11 def run(self):
12 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossumf3ee46b2001-04-15 00:42:13 +000013 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Guido van Rossum66172522001-04-06 16:32:22 +000014 sock.bind((HOST, PORT))
15 sock.listen(1)
16 conn, client = sock.accept()
17 buffer = ""
18 while "\n" not in buffer:
19 data = conn.recv(10)
20 if not data:
21 break
22 buffer = buffer + data
23 while buffer:
24 n = conn.send(buffer)
25 buffer = buffer[n:]
26 conn.close()
27 sock.close()
28
29class echo_client(asynchat.async_chat):
30
31 def __init__(self):
32 asynchat.async_chat.__init__(self)
33 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
34 self.connect((HOST, PORT))
35 self.set_terminator("\n")
36 self.buffer = ""
Guido van Rossum66172522001-04-06 16:32:22 +000037
38 def handle_connect(self):
39 print "Connected"
40
41 def collect_incoming_data(self, data):
42 self.buffer = self.buffer + data
43
44 def found_terminator(self):
45 print "Received:", `self.buffer`
46 self.buffer = ""
47 self.close()
48
49def main():
50 s = echo_server()
51 s.start()
Guido van Rossumdca060c2001-04-06 16:43:49 +000052 time.sleep(1) # Give server time to initialize
Guido van Rossum66172522001-04-06 16:32:22 +000053 c = echo_client()
Guido van Rossumdca060c2001-04-06 16:43:49 +000054 c.push("hello ")
55 c.push("world\n")
Guido van Rossum66172522001-04-06 16:32:22 +000056 asyncore.loop()
57
58main()