1
# IVLE - Informatics Virtual Learning Environment
2
# Copyright (C) 2007-2008 The University of Melbourne
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19
# Author: Thomas Conway
30
def start_server(port, magic, daemon_mode, handler, initializer = None):
31
# Attempt to open the socket.
32
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
36
# Excellent! It worked. Let's turn ourself into a daemon,
37
# then get on with the job of being a python interpreter.
39
if os.fork(): # launch child and...
40
os._exit(0) # kill off parent
42
if os.fork(): # launch child and...
43
os._exit(0) # kill off parent again.
50
(conn, addr) = s.accept()
53
buf = cStringIO.StringIO()
58
blk = conn.recv(1024, socket.MSG_DONTWAIT)
60
# Exception thrown if it WOULD block (but we
61
# told it not to wait) - ie. we are done
64
env = cjson.decode(inp)
66
# Check that the message is
67
digest = md5.new(env['content'] + magic).digest().encode('hex')
68
if env['digest'] != digest:
72
content = cjson.decode(env['content'])
74
response = handler(content)
76
conn.sendall(cjson.encode(response))
80
# Make a JSON object full of exceptional goodness
81
tb_dump = cStringIO.StringIO()
82
e_type, e_val, e_tb = sys.exc_info()
83
traceback.print_tb(e_tb, file=tb_dump)
85
"type": e_type.__name__,
87
"traceback": tb_dump.getvalue()
89
conn.sendall(cjson.encode(json_exc))
93
def chat(host, port, msg, magic, decode = True):
94
sok = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
95
sok.connect((host, port))
96
content = cjson.encode(msg)
97
digest = md5.new(content + magic).digest().encode("hex")
98
env = {'digest':digest,'content':content}
99
sok.send(cjson.encode(env))
101
buf = cStringIO.StringIO()
106
blk = conn.recv(1024, socket.MSG_DONTWAIT)
108
# Exception thrown if it WOULD block (but we
109
# told it not to wait) - ie. we are done
115
return cjson.decode(inp)