64 lines
2.1 KiB
Python
64 lines
2.1 KiB
Python
# uncompyle6 version 3.9.2
|
|
# Python bytecode version base 3.7.0 (3394)
|
|
# Decompiled from: Python 3.8.19 (default, Mar 20 2024, 15:27:52)
|
|
# [Clang 14.0.6 ]
|
|
# Embedded file name: /var/user/app/device_supervisorbak/device_supervisor/lib/pycomm3/socket_.py
|
|
# Compiled at: 2024-04-18 03:12:57
|
|
# Size of source mod 2**32: 2788 bytes
|
|
import logging, socket, struct
|
|
from .exceptions import CommError
|
|
from .const import HEADER_SIZE
|
|
|
|
class Socket:
|
|
_Socket__log = logging.getLogger(f"{__module__}.{__qualname__}")
|
|
|
|
def __init__(self, timeout=5.0):
|
|
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
self.sock.settimeout(timeout)
|
|
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
|
|
|
|
def connect(self, host, port):
|
|
try:
|
|
self.sock.connect((host, port))
|
|
except socket.timeout:
|
|
raise CommError("Socket timeout during connection.")
|
|
|
|
def send(self, msg, timeout=0):
|
|
if timeout != 0:
|
|
self.sock.settimeout(timeout)
|
|
total_sent = 0
|
|
while total_sent < len(msg):
|
|
try:
|
|
sent = self.sock.send(msg[total_sent[:None]])
|
|
if sent == 0:
|
|
raise CommError("socket connection broken.")
|
|
total_sent += sent
|
|
except socket.error as err:
|
|
try:
|
|
raise CommError("socket connection broken.") from err
|
|
finally:
|
|
err = None
|
|
del err
|
|
|
|
return total_sent
|
|
|
|
def receive(self, timeout=0):
|
|
try:
|
|
if timeout != 0:
|
|
self.sock.settimeout(timeout)
|
|
data = self.sock.recv(4096)
|
|
data_len = struct.unpack_from("<H", data, 2)[0]
|
|
while len(data) - HEADER_SIZE < data_len:
|
|
data += self.sock.recv(4096)
|
|
|
|
return data
|
|
except socket.error as err:
|
|
try:
|
|
raise CommError("socket connection broken") from err
|
|
finally:
|
|
err = None
|
|
del err
|
|
|
|
def close(self):
|
|
self.sock.close()
|