-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp_server.py
63 lines (53 loc) · 1.19 KB
/
tcp_server.py
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
'''
A TCP server
'''
import socket
import time
def greeting(c, who):
print 'received connection from', who
c.sendall('Hello!')
c.close()
def heartbeat(c, who):
print 'received connection from', who
for i in xrange(10):
c.sendall(time.ctime())
time.sleep(1)
c.close()
def server(handler, host='localhost', port=9005):
s = socket.socket()
s.bind((host, port))
s.listen(5)
print 'listening for connections...'
try:
while True:
c, who = s.accept()
handler(c, who)
# print 'received connection from', who
# c.sendall('Hello!')
# c.close()
except KeyboardInterrupt:
print '\nGoodbye!'
finally:
s.close()
if __name__ == '__main__':
# server(greeting)
server(heartbeat)
# s = socket.socket()
# address = 'localhost', 9002
# binds the server
# s.bind(address)
# listen on the configured port, the 5 is a "standard" value
# s.listen(5)
# print 'listening for connections...'
# accepts returns a tuple: a connection socket, and the source (tuple address, port)
# try:
# while True:
# c, who = s.accept()
# greeting(c,who)
# # print 'received connection from', who
# # c.sendall('Hello!')
# # c.close()
# except KeyboardInterrupt:
# print '\nGoodbye!'
# finally:
# s.close()