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
28
def start_server(port, magic, daemon_mode, handler, initializer = None):
29
# Attempt to open the socket.
30
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
34
# Excellent! It worked. Let's turn ourself into a daemon,
35
# then get on with the job of being a python interpreter.
37
if os.fork(): # launch child and...
38
os._exit(0) # kill off parent
40
if os.fork(): # launch child and...
41
os._exit(0) # kill off parent again.
48
(conn, addr) = s.accept()
51
buf = cStringIO.StringIO()
56
blk = conn.recv(1024, socket.MSG_DONTWAIT)
58
# Exception thrown if it WOULD block (but we
59
# told it not to wait) - ie. we are done
62
env = cjson.decode(inp)
64
# Check that the message is
65
digest = md5.new(env['content'] + magic).digest().encode('hex')
66
if env['digest'] != digest:
70
content = cjson.decode(env['content'])
72
response = handler(content)
74
conn.sendall(cjson.encode(response))
78
conn.sendall(cjson.encode(repr(e)))
82
def chat(host, port, msg, magic, decode = True):
83
sok = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
84
sok.connect((host, port))
85
content = cjson.encode(msg)
86
digest = md5.new(content + magic).digest().encode("hex")
87
env = {'digest':digest,'content':content}
88
sok.send(cjson.encode(env))
90
buf = cStringIO.StringIO()
95
blk = conn.recv(1024, socket.MSG_DONTWAIT)
97
# Exception thrown if it WOULD block (but we
98
# told it not to wait) - ie. we are done
104
return cjson.decode(inp)