Only define new line once
This commit is contained in:
parent
6920b43567
commit
c20a567709
3 changed files with 12 additions and 6 deletions
|
@ -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)
|
||||
|
|
|
@ -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]
|
||||
|
||||
|
||||
|
|
|
@ -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]
|
||||
|
|
Reference in a new issue