This commit was manufactured by cvs2svn to create tag 'r211c1'.
[python/dscho.git] / Lib / test / test_asynchat.py
blob60017e0ab53d9d8c66723870c5ac380c1894b543
1 # test asynchat -- requires threading
3 import thread # If this fails, we can't test this module
4 import asyncore, asynchat, socket, threading, time
6 HOST = "127.0.0.1"
7 PORT = 54321
9 class echo_server(threading.Thread):
11 def run(self):
12 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
13 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
14 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()
29 class echo_client(asynchat.async_chat):
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 = ""
38 def handle_connect(self):
39 print "Connected"
41 def collect_incoming_data(self, data):
42 self.buffer = self.buffer + data
44 def found_terminator(self):
45 print "Received:", `self.buffer`
46 self.buffer = ""
47 self.close()
49 def main():
50 s = echo_server()
51 s.start()
52 time.sleep(1) # Give server time to initialize
53 c = echo_client()
54 c.push("hello ")
55 c.push("world\n")
56 asyncore.loop()
58 main()