-
Notifications
You must be signed in to change notification settings - Fork 1
/
ashmon.py
77 lines (64 loc) · 2.09 KB
/
ashmon.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python
"""ash connection management.
ash can run as daemon, establish connection."""
__author__ = "SeongJae Park"
__email__ = "[email protected]"
__copyright__ = "Copyright (c) 2011-2013, SeongJae Park"
__license__ = "GPLv3"
import socket
import threading
import ash
ASH_CONN_PORT = 13131
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', ASH_CONN_PORT))
s.listen(1)
_stop_accepting = False
_stop_listening = False
def start_daemon():
HOST = ''
_stop_listening = False
listener = _AcceptorThread()
listener.start()
def stop_daemon():
_stop_accepting = True
class _AcceptorThread(threading.Thread):
def run(self):
global s
while True:
if _stop_accepting:
global _stop_listening
_stop_listening = True
break
conn, addr = s.accept()
print "connected by ash. start listener"
listener = _ListenerThread(conn)
listener.start()
_MAX_SOCKET_BUFFER_SIZE = 1024
END_OF_MSG = 'end_of_expr'
# combine tokens received from socket, get complete message peer sent.
def get_complete_message(token, pre_tokens):
pre_tokens += token
complete_msgs = []
while END_OF_MSG in pre_tokens:
complete_msgs.append(pre_tokens[:pre_tokens.find(END_OF_MSG)])
pre_tokens = pre_tokens[pre_tokens.find(END_OF_MSG) + len(END_OF_MSG):]
return complete_msgs, pre_tokens
class _ListenerThread(threading.Thread):
def __init__(self, conn):
threading.Thread.__init__(self)
self.conn = conn
def run(self):
tokens = ''
while True:
if _stop_listening:
break
received = self.conn.recv(1024)
if not received:
print "not received! stop listening!"
break
msgs, tokens = get_complete_message(received, tokens)
for msg in msgs:
result = ash.input(msg)
self.conn.sendall("%s%s" % (result, END_OF_MSG))
self.conn.close()