Warning: Can't synchronize with repository "(default)" (Unsupported version control system "svn": No module named svn). Look in the Trac log for more information.

Ticket #1713: test_socket_server.py

File test_socket_server.py, 1.7 KB (added by Chris Arndt, 4 years ago)

Minimal socket test server that emulates cherrypy.WSGIServer behaviour

Line 
1#!/usr/bin/env python
2"""Test socket connections on Ubuntu.
3
4Show specific behaviour when using ``socket.getaddrinfo`` with host argument
5set to ``None``.
6
7In this case, the address info for IPV6 will be returned first, so when the
8server listen socket is created based on this info, it will be IPV6, and when a
9client connects, its address will be a IPV6 address.
10
11Example client code::
12
13    import socket
14    host = 'localhost'
15    port = 8080
16    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
17    s.connect((host, port))
18    s.close()
19"""
20
21import socket
22import sys
23
24def main(args):
25    sock = None
26    flags = 0
27
28    try:
29        host = args.pop(0)
30        port = args.pop(0)
31    except:
32        host = ''
33        # Uncomment following line and comment out line above for testing
34        # differing behaviour related to IPV6.
35        #host = '0.0.0.0'
36        port = 8080
37
38    if host == '':
39        host = None
40        flags = socket.AI_PASSIVE
41    info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM,
42        0, flags)
43    print info
44
45    af, socktype, proto, canonname, sa = info[0]
46    try:
47        sock = socket.socket(af, socktype, proto)
48        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
49        sock.bind((host or '', port))
50    except socket.error, msg:
51        if sock:
52            sock.close()
53        print "Error: could not open socket '%s' port %s'" % (host, port)
54        return 1
55    else:
56        sock.listen(1)
57        print "Listening on '%s' port %s'" % (host, port)
58
59    while True:
60        try:
61            s, addr = sock.accept()
62            print "Remote address: %s" % (addr,)
63        except KeyboardInterrupt:
64            break
65    return 0
66
67if __name__ == '__main__':
68    sys.exit(main(sys.argv[1:]))