diff options
author | Sébastien Dailly <sebastien@dailly.me> | 2023-07-15 14:44:41 +0200 |
---|---|---|
committer | Sébastien Dailly <sebastien@dailly.me> | 2023-07-15 14:59:43 +0200 |
commit | 02d676bda89c2fb8469ea81f7429c19c1e29df7c (patch) | |
tree | 11dae86a561a4800661e6c174b47611a704f857e /socket_conn.py |
Initial commit
Diffstat (limited to 'socket_conn.py')
-rwxr-xr-x | socket_conn.py | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/socket_conn.py b/socket_conn.py new file mode 100755 index 0000000..0ac7230 --- /dev/null +++ b/socket_conn.py @@ -0,0 +1,46 @@ +#
+# Describe a connection over a socket.
+#
+# This class is intended to be apdapted into IEndpoint interface
+
+import socket
+from zope import interface
+import errno
+
+from interfaces import endpoint
+
+from zope import component
+from interfaces.message import Debug
+
+@interface.implementer(endpoint.IConnection)
+class SocketConnection(object):
+ """ Define a connected element (serial, network…)
+ """
+
+ def __init__(self, configuration):
+ self.port = int(configuration["port"])
+ self.host = configuration["host"]
+
+ def connect(self) -> None:
+ """ Connect """
+ self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.s.connect((self.host, self.port))
+ self.s.settimeout(0.0)
+ component.handle(Debug("Connected to the socket"))
+
+ def read(self) -> str:
+ """ Read from the connection and return the bytes.
+ Return None if there is nothing to read (non-blocking)
+ Raise an exception if disconnected """
+ try:
+ return self.s.recv(1024)
+ except socket.error as e:
+ err = e.args[0]
+ if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
+ return None
+ raise e
+
+ def write(self, content:str) -> None:
+ """ Write into the connection.
+ Raise an exception if disconnected """
+ self.s.sendall(content)
|