-
Notifications
You must be signed in to change notification settings - Fork 0
/
echoserver
executable file
·64 lines (52 loc) · 1.68 KB
/
echoserver
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
"""
usage: echoserver [HOST [PORT]]
TODO: properly support IPv4 hostnames
"""
import sys
import socket
import SocketServer
class EchoServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
class EchoServerV6(EchoServer):
address_family = socket.AF_INET6
class EchoRequestHandler(SocketServer.StreamRequestHandler):
"""
Handle one connection from a client.
"""
def handle(self):
print "connection from %s" % self.client_address[0]
while True:
line = self.rfile.readline()
if not line: break
print "%s wrote: %r" % (self.client_address[0], line.rstrip())
self.wfile.write(line)
print "%s disconnected" % self.client_address[0]
def serve(host, port):
# TODO: we should choose the IPv4 server class if we're given an IPv4
# hostname/address
server = EchoServerV6((host, port), EchoRequestHandler)
if len(server.server_address) == 2:
print "server listening on %s:%s" % server.server_address
else:
print "server listening on [%s]:%s" % server.server_address[0:2]
if server.socket.getsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY):
print '(IPv6 only)'
else:
print '(dual stack IPv6 and IPv4)'
try:
server.serve_forever()
except KeyboardInterrupt:
pass
print "shutting down; waiting for connenctions to close..."
server.shutdown()
if __name__ == '__main__':
host, port = '', 5000
if len(sys.argv) > 1:
host = sys.argv[1]
if len(sys.argv) > 2:
port = int(sys.argv[2])
try:
serve(host, port)
except KeyboardInterrupt:
print ''