From c20a567709e3e2a77bbfdb91e58f13f2c32be45f Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Sat, 8 Dec 2018 14:36:37 +0000 Subject: [PATCH] Only define new line once --- ipc_unix/pubsub.py | 9 +++++++-- ipc_unix/simple.py | 4 ++-- ipc_unix/utils.py | 5 +++-- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/ipc_unix/pubsub.py b/ipc_unix/pubsub.py index a2c8ce0..1189c96 100644 --- a/ipc_unix/pubsub.py +++ b/ipc_unix/pubsub.py @@ -4,7 +4,12 @@ import socket import threading import ujson -from ipc_unix.utils import DEFAULT_SOCKET_READ_TIMEOUT, read_payload, socket_has_data +from ipc_unix.utils import ( + DEFAULT_SOCKET_READ_TIMEOUT, + NEW_LINE, + read_payload, + socket_has_data, +) class Subscriber: @@ -93,7 +98,7 @@ class Publisher: dead_sockets = [] if writable: - data = ujson.dumps(message).encode() + b"\n" + data = ujson.dumps(message).encode() + NEW_LINE for sock in writable: try: sock.send(data) diff --git a/ipc_unix/simple.py b/ipc_unix/simple.py index 5aad761..7f76ee0 100644 --- a/ipc_unix/simple.py +++ b/ipc_unix/simple.py @@ -4,7 +4,7 @@ import socketserver import threading import ujson -from ipc_unix.utils import read_payload +from ipc_unix.utils import NEW_LINE, read_payload class Client: @@ -14,7 +14,7 @@ class Client: def send(self, data: dict): with socket.socket(socket.AF_UNIX, type=socket.SOCK_STREAM) as sock: sock.connect(self.socket_path) - sock.sendall(ujson.dumps(data).encode() + b"\n") + sock.sendall(ujson.dumps(data).encode() + NEW_LINE) return read_payload(sock)[0] diff --git a/ipc_unix/utils.py b/ipc_unix/utils.py index 8c354d2..7d7153d 100644 --- a/ipc_unix/utils.py +++ b/ipc_unix/utils.py @@ -4,6 +4,7 @@ import ujson BUFFER_SIZE = 4096 DEFAULT_SOCKET_READ_TIMEOUT = 0.01 +NEW_LINE = b"\n" def socket_has_data(sock, timeout=DEFAULT_SOCKET_READ_TIMEOUT) -> bool: @@ -13,11 +14,11 @@ def socket_has_data(sock, timeout=DEFAULT_SOCKET_READ_TIMEOUT) -> bool: def read_payload(payload): data = b"" - while b"\n" not in data: + while NEW_LINE not in data: if not socket_has_data(payload): break message = payload.recv(BUFFER_SIZE) if message == b"": break data += message - return [ujson.loads(row) for row in data.split(b"\n") if row] + return [ujson.loads(row) for row in data.split(NEW_LINE) if row]