~dkuhlman/python-training-materials/Materials

« back to all changes in this revision

Viewing changes to Exercises_python/Solutions/socket_echo_server.py

  • Committer: Dave Kuhlman
  • Date: 2015-10-03 18:25:17 UTC
  • mfrom: (35.1.5 Materials)
  • Revision ID: dkuhlman@davekuhlman.org-20151003182517-b2m7eltjdapw46zh
Review for Cisco.  Merged checkpoint 10

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
 
 
3
"""
 
4
Synopsis:
 
5
    Implement a server that uses a low level Python socket to echo a response.
 
6
    Use the "socket" module in the Python standard library.
 
7
Usage:
 
8
    python socket_echo_server.py
 
9
Resources:
 
10
    The Python socket module -- https://docs.python.org/2/library/socket.html
 
11
"""
 
12
 
 
13
import socket
 
14
 
 
15
 
 
16
def serve():
 
17
    HOST = ''                 # Symbolic name meaning all available interfaces
 
18
    PORT = 50007              # Arbitrary non-privileged port
 
19
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
20
    sock.bind((HOST, PORT))
 
21
    sock.listen(1)
 
22
    conn, addr = sock.accept()
 
23
    print 'Connected by', addr
 
24
    while True:
 
25
        data = conn.recv(1024)
 
26
        if not data:
 
27
            break
 
28
        data = data.upper()
 
29
        conn.sendall(data)
 
30
    conn.close()
 
31
 
 
32
 
 
33
def main():
 
34
    serve()
 
35
 
 
36
 
 
37
if __name__ == '__main__':
 
38
    main()