diff options
Diffstat (limited to 'runtime/tools/demoserver.py')
-rw-r--r-- | runtime/tools/demoserver.py | 58 |
1 files changed, 34 insertions, 24 deletions
diff --git a/runtime/tools/demoserver.py b/runtime/tools/demoserver.py index c72a58b739..0f6a3740c6 100644 --- a/runtime/tools/demoserver.py +++ b/runtime/tools/demoserver.py @@ -11,49 +11,59 @@ # # See ":help channel-demo" in Vim. -import SocketServer +from __future__ import print_function import json import socket import sys import threading +try: + # Python 3 + import socketserver +except ImportError: + # Python 2 + import SocketServer as socketserver + thesocket = None -class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): +class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler): def handle(self): - print "=== socket opened ===" + print("=== socket opened ===") global thesocket thesocket = self.request while True: try: - data = self.request.recv(4096) + data = self.request.recv(4096).decode('utf-8') except socket.error: - print "=== socket error ===" + print("=== socket error ===") break except IOError: - print "=== socket closed ===" + print("=== socket closed ===") break if data == '': - print "=== socket closed ===" + print("=== socket closed ===") break - print "received: {}".format(data) + print("received: {}".format(data)) try: decoded = json.loads(data) except ValueError: - print "json decoding failed" - decoded = [0, ''] + print("json decoding failed") + decoded = [-1, ''] - if decoded[1] == 'hello!': - response = "got it" - else: - response = "what?" - encoded = json.dumps([decoded[0], response]) - print "sending {}".format(encoded) - self.request.sendall(encoded) + # Send a response if the sequence number is positive. + # Negative numbers are used for "eval" responses. + if decoded[0] >= 0: + if decoded[1] == 'hello!': + response = "got it" + else: + response = "what?" + encoded = json.dumps([decoded[0], response]) + print("sending {}".format(encoded)) + self.request.sendall(encoded.encode('utf-8')) thesocket = None -class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): +class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): pass if __name__ == "__main__": @@ -69,19 +79,19 @@ if __name__ == "__main__": # Exit the server thread when the main thread terminates server_thread.daemon = True server_thread.start() - print "Server loop running in thread: ", server_thread.name + print("Server loop running in thread: ", server_thread.name) - print "Listening on port {}".format(PORT) + print("Listening on port {}".format(PORT)) while True: typed = sys.stdin.readline() if "quit" in typed: - print "Goodbye!" + print("Goodbye!") break if thesocket is None: - print "No socket yet" + print("No socket yet") else: - print "sending {}".format(typed) - thesocket.sendall(typed) + print("sending {}".format(typed)) + thesocket.sendall(typed.encode('utf-8')) server.shutdown() server.server_close() |