blob: c72a58b739f17bf6e092d319a262ed96d972f32d [file] [log] [blame]
Bram Moolenaar3b5f9292016-01-28 22:37:01 +01001#!/usr/bin/python
2# Server that will accept connections from a Vim channel.
3# Run this server and then in Vim you can open the channel:
4# :let handle = connect('localhost:8765', 'json')
5#
6# Then Vim can send requests to the server:
7# :let response = sendexpr(handle, 'hello!')
8#
9# And you can control Vim by typing a JSON message here, e.g.:
10# ["ex","echo 'hi there'"]
11#
12# See ":help channel-demo" in Vim.
13
14import SocketServer
15import json
16import socket
17import sys
18import threading
19
20thesocket = None
21
22class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
23
24 def handle(self):
25 print "=== socket opened ==="
26 global thesocket
27 thesocket = self.request
28 while True:
29 try:
30 data = self.request.recv(4096)
31 except socket.error:
32 print "=== socket error ==="
33 break
34 except IOError:
35 print "=== socket closed ==="
36 break
37 if data == '':
38 print "=== socket closed ==="
39 break
40 print "received: {}".format(data)
41 try:
42 decoded = json.loads(data)
43 except ValueError:
44 print "json decoding failed"
45 decoded = [0, '']
46
47 if decoded[1] == 'hello!':
48 response = "got it"
49 else:
50 response = "what?"
51 encoded = json.dumps([decoded[0], response])
52 print "sending {}".format(encoded)
53 self.request.sendall(encoded)
54 thesocket = None
55
56class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
57 pass
58
59if __name__ == "__main__":
60 HOST, PORT = "localhost", 8765
61
62 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
63 ip, port = server.server_address
64
65 # Start a thread with the server -- that thread will then start one
66 # more thread for each request
67 server_thread = threading.Thread(target=server.serve_forever)
68
69 # Exit the server thread when the main thread terminates
70 server_thread.daemon = True
71 server_thread.start()
72 print "Server loop running in thread: ", server_thread.name
73
74 print "Listening on port {}".format(PORT)
75 while True:
76 typed = sys.stdin.readline()
77 if "quit" in typed:
78 print "Goodbye!"
79 break
80 if thesocket is None:
81 print "No socket yet"
82 else:
83 print "sending {}".format(typed)
84 thesocket.sendall(typed)
85
86 server.shutdown()
87 server.server_close()