/Demo/sockets/echosvr.py

http://unladen-swallow.googlecode.com/ · Python · 31 lines · 20 code · 5 blank · 6 comment · 4 complexity · 225f1c84c2b40234d26ba133a0795d7f MD5 · raw file

  1. #! /usr/bin/env python
  2. # Python implementation of an 'echo' tcp server: echo all data it receives.
  3. #
  4. # This is the simplest possible server, servicing a single request only.
  5. import sys
  6. from socket import *
  7. # The standard echo port isn't very useful, it requires root permissions!
  8. # ECHO_PORT = 7
  9. ECHO_PORT = 50000 + 7
  10. BUFSIZE = 1024
  11. def main():
  12. if len(sys.argv) > 1:
  13. port = int(eval(sys.argv[1]))
  14. else:
  15. port = ECHO_PORT
  16. s = socket(AF_INET, SOCK_STREAM)
  17. s.bind(('', port))
  18. s.listen(1)
  19. conn, (remotehost, remoteport) = s.accept()
  20. print 'connected by', remotehost, remoteport
  21. while 1:
  22. data = conn.recv(BUFSIZE)
  23. if not data:
  24. break
  25. conn.send(data)
  26. main()