File: simple_rpc.py

package info (click to toggle)
k3d 0.8.0.2-6
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 40,692 kB
  • ctags: 39,695
  • sloc: cpp: 171,303; ansic: 24,129; xml: 6,995; python: 5,796; makefile: 726; sh: 22
file content (63 lines) | stat: -rw-r--r-- 1,792 bytes parent folder | download | duplicates (5)
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
#python

# This script uses Python to start an interactive "K-3D server" that listens for
# Python commands on port 8888, executing each command and printing its output.
# Although this example is a toy (a real RPC server wouldn't incorporate interactive
# Python prompts into its output, for example), it demonstrates how K-3D can be
# easily integrated into larger systems.
#
# To start a K-3D "server", do the following at the shell:
#
# $ k3d --ui=none --script-file=/path/to/simple_rpc.py
#
# To communicate with the running K-3D "server" use netcat to send interactive
# Python "commands":
#
# $ nc localhost 8888
#
# You can use "exit()" or "quit()" to end a client session cleanly.  You will
# have to use Ctrl-C or similar to end the server process.

import code
import k3d
import sys
import SocketServer

console = code.InteractiveConsole()
console.push("__close = False\n")
console.push("def exit():\n  global __close\n  __close = True\n")
console.push("def quit():\n  global __close\n  __close = True\n")

class request_handler(SocketServer.BaseRequestHandler):

	def __init__(self, request, client_address, server):
		sys.stdout = self
		sys.stderr = self

		SocketServer.BaseRequestHandler.__init__(self, request, client_address, server)

	def write(self, output):
		self.request.send(output)

	def handle(self):
		global console
		console.locals["__close"] = False

		sys.stdout.write(">>> ")
		while True:
			more_input = console.push(self.request.recv(1024))

			if console.locals["__close"]:
				break

			if more_input:
				sys.stdout.write("... ")
			else:
				sys.stdout.write(">>> ")
    
address = ("localhost", 8888)
server = SocketServer.TCPServer(address, request_handler)

k3d.log.info("K-3D listening for Python commands on port 8888 ...")
server.serve_forever()