This repository has been archived on 2023-03-26. You can view files and clone it, but cannot push or open issues or pull requests.
ipc-unix/ipc_unix/simple.py

47 lines
1.3 KiB
Python
Raw Normal View History

2018-12-07 23:34:59 +00:00
import socket
2018-12-07 20:35:34 +00:00
import socketserver
import threading
2018-12-07 20:44:31 +00:00
2018-12-07 20:35:34 +00:00
import ujson
from ipc_unix.utils import read_payload
def send_to(socket_path, data: dict):
2018-12-07 23:34:59 +00:00
with socket.socket(socket.AF_UNIX, type=socket.SOCK_STREAM) as sock:
sock.connect(socket_path)
sock.sendall(ujson.dumps(data).encode() + b"\n")
return read_payload(sock)[0]
2018-12-07 23:34:59 +00:00
2018-12-07 20:35:34 +00:00
class RequestHandler(socketserver.BaseRequestHandler):
def handle_request(self, request: dict):
2018-12-07 20:35:34 +00:00
raise NotImplementedError("Failed to override `handle_request`")
def handle(self):
data = read_payload(self.request)[0]
2018-12-07 20:35:34 +00:00
response = self.handle_request(data)
self.request.sendall(ujson.dumps(response).encode())
class Server:
def __init__(self, socket_path):
class InstanceRequestHandler(RequestHandler):
handle_request = self.handle_request
self.server = socketserver.UnixStreamServer(socket_path, InstanceRequestHandler)
def serve_forever(self):
self.server.serve_forever()
def serve_in_thread(self):
thread = threading.Thread(target=self.serve_forever)
thread.start()
return thread
def close(self):
2018-12-08 13:07:51 +00:00
self.server.shutdown()
2018-12-07 20:35:34 +00:00
self.server.server_close()
def handle_request(self, request: dict):
2018-12-07 20:35:34 +00:00
raise NotImplementedError("Must override `handle_request`")