Guido van Rossum | 6617252 | 2001-04-06 16:32:22 +0000 | [diff] [blame] | 1 | # test asynchat -- requires threading |
| 2 | |
Guido van Rossum | 9df3eab | 2001-04-14 14:35:43 +0000 | [diff] [blame] | 3 | import thread # If this fails, we can't test this module |
Guido van Rossum | dca060c | 2001-04-06 16:43:49 +0000 | [diff] [blame] | 4 | import asyncore, asynchat, socket, threading, time |
Guido van Rossum | 6617252 | 2001-04-06 16:32:22 +0000 | [diff] [blame] | 5 | |
| 6 | HOST = "127.0.0.1" |
| 7 | PORT = 54321 |
| 8 | |
| 9 | class echo_server(threading.Thread): |
| 10 | |
| 11 | def run(self): |
| 12 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
Guido van Rossum | f3ee46b | 2001-04-15 00:42:13 +0000 | [diff] [blame] | 13 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
Guido van Rossum | 6617252 | 2001-04-06 16:32:22 +0000 | [diff] [blame] | 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() |
| 28 | |
| 29 | class 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 Rossum | 6617252 | 2001-04-06 16:32:22 +0000 | [diff] [blame] | 37 | |
| 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 | |
| 49 | def main(): |
| 50 | s = echo_server() |
| 51 | s.start() |
Guido van Rossum | dca060c | 2001-04-06 16:43:49 +0000 | [diff] [blame] | 52 | time.sleep(1) # Give server time to initialize |
Guido van Rossum | 6617252 | 2001-04-06 16:32:22 +0000 | [diff] [blame] | 53 | c = echo_client() |
Guido van Rossum | dca060c | 2001-04-06 16:43:49 +0000 | [diff] [blame] | 54 | c.push("hello ") |
| 55 | c.push("world\n") |
Guido van Rossum | 6617252 | 2001-04-06 16:32:22 +0000 | [diff] [blame] | 56 | asyncore.loop() |
| 57 | |
| 58 | main() |