Guido van Rossum | f06ee5f | 1996-11-27 19:52:01 +0000 | [diff] [blame] | 1 | #! /usr/bin/env python |
Guido van Rossum | 22825e8 | 1991-07-01 18:32:32 +0000 | [diff] [blame] | 2 | |
| 3 | # Python implementation of an 'echo' tcp server: echo all data it receives. |
| 4 | # |
Guido van Rossum | 1134991 | 1995-01-12 12:41:20 +0000 | [diff] [blame] | 5 | # This is the simplest possible server, servicing a single request only. |
Guido van Rossum | 22825e8 | 1991-07-01 18:32:32 +0000 | [diff] [blame] | 6 | |
| 7 | import sys |
| 8 | from socket import * |
| 9 | |
| 10 | # The standard echo port isn't very useful, it requires root permissions! |
| 11 | # ECHO_PORT = 7 |
| 12 | ECHO_PORT = 50000 + 7 |
| 13 | BUFSIZE = 1024 |
| 14 | |
| 15 | def main(): |
Tim Peters | e6ddc8b | 2004-07-18 05:56:09 +0000 | [diff] [blame] | 16 | if len(sys.argv) > 1: |
| 17 | port = int(eval(sys.argv[1])) |
| 18 | else: |
| 19 | port = ECHO_PORT |
| 20 | s = socket(AF_INET, SOCK_STREAM) |
| 21 | s.bind(('', port)) |
| 22 | s.listen(1) |
| 23 | conn, (remotehost, remoteport) = s.accept() |
Collin Winter | 6f2df4d | 2007-07-17 20:59:35 +0000 | [diff] [blame^] | 24 | print('connected by', remotehost, remoteport) |
Tim Peters | e6ddc8b | 2004-07-18 05:56:09 +0000 | [diff] [blame] | 25 | while 1: |
| 26 | data = conn.recv(BUFSIZE) |
| 27 | if not data: |
| 28 | break |
| 29 | conn.send(data) |
Guido van Rossum | 22825e8 | 1991-07-01 18:32:32 +0000 | [diff] [blame] | 30 | |
| 31 | main() |