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 threading
|
||||||
|
|
||||||
import ujson
|
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:
|
class Subscriber:
|
||||||
|
@ -93,7 +98,7 @@ class Publisher:
|
||||||
dead_sockets = []
|
dead_sockets = []
|
||||||
|
|
||||||
if writable:
|
if writable:
|
||||||
data = ujson.dumps(message).encode() + b"\n"
|
data = ujson.dumps(message).encode() + NEW_LINE
|
||||||
for sock in writable:
|
for sock in writable:
|
||||||
try:
|
try:
|
||||||
sock.send(data)
|
sock.send(data)
|
||||||
|
|
|
@ -4,7 +4,7 @@ import socketserver
|
||||||
import threading
|
import threading
|
||||||
|
|
||||||
import ujson
|
import ujson
|
||||||
from ipc_unix.utils import read_payload
|
from ipc_unix.utils import NEW_LINE, read_payload
|
||||||
|
|
||||||
|
|
||||||
class Client:
|
class Client:
|
||||||
|
@ -14,7 +14,7 @@ class Client:
|
||||||
def send(self, data: dict):
|
def send(self, data: dict):
|
||||||
with socket.socket(socket.AF_UNIX, type=socket.SOCK_STREAM) as sock:
|
with socket.socket(socket.AF_UNIX, type=socket.SOCK_STREAM) as sock:
|
||||||
sock.connect(self.socket_path)
|
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]
|
return read_payload(sock)[0]
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -4,6 +4,7 @@ import ujson
|
||||||
|
|
||||||
BUFFER_SIZE = 4096
|
BUFFER_SIZE = 4096
|
||||||
DEFAULT_SOCKET_READ_TIMEOUT = 0.01
|
DEFAULT_SOCKET_READ_TIMEOUT = 0.01
|
||||||
|
NEW_LINE = b"\n"
|
||||||
|
|
||||||
|
|
||||||
def socket_has_data(sock, timeout=DEFAULT_SOCKET_READ_TIMEOUT) -> bool:
|
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):
|
def read_payload(payload):
|
||||||
data = b""
|
data = b""
|
||||||
while b"\n" not in data:
|
while NEW_LINE not in data:
|
||||||
if not socket_has_data(payload):
|
if not socket_has_data(payload):
|
||||||
break
|
break
|
||||||
message = payload.recv(BUFFER_SIZE)
|
message = payload.recv(BUFFER_SIZE)
|
||||||
if message == b"":
|
if message == b"":
|
||||||
break
|
break
|
||||||
data += message
|
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