Guido van Rossum | 6617252 | 2001-04-06 16:32:22 +0000 | [diff] [blame] | 1 | # test asynchat -- requires threading |
| 2 | |
Guido van Rossum | dca060c | 2001-04-06 16:43:49 +0000 | [diff] [blame] | 3 | import asyncore, asynchat, socket, threading, time |
Guido van Rossum | 6617252 | 2001-04-06 16:32:22 +0000 | [diff] [blame] | 4 | |
| 5 | HOST = "127.0.0.1" |
| 6 | PORT = 54321 |
| 7 | |
| 8 | class 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 | |
| 27 | class 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 Rossum | 6617252 | 2001-04-06 16:32:22 +0000 | [diff] [blame] | 35 | |
| 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 | |
| 47 | def main(): |
| 48 | s = echo_server() |
| 49 | s.start() |
Guido van Rossum | dca060c | 2001-04-06 16:43:49 +0000 | [diff] [blame] | 50 | time.sleep(1) # Give server time to initialize |
Guido van Rossum | 6617252 | 2001-04-06 16:32:22 +0000 | [diff] [blame] | 51 | c = echo_client() |
Guido van Rossum | dca060c | 2001-04-06 16:43:49 +0000 | [diff] [blame] | 52 | c.push("hello ") |
| 53 | c.push("world\n") |
Guido van Rossum | 6617252 | 2001-04-06 16:32:22 +0000 | [diff] [blame] | 54 | asyncore.loop() |
| 55 | |
| 56 | main() |