aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSébastien Dailly <sebastien@dailly.me>2024-04-13 22:59:43 +0200
committerSébastien Dailly <sebastien@dailly.me>2024-04-13 22:59:43 +0200
commit89d3bb2421a42dccd4f159b77e9f7fb103a4f8b8 (patch)
treeedc50f8e27a8aba6449297a425e46d2d34378c32
parentc27035a029cdcbfb854ea0760fd083b5d8870c6d (diff)
Reliable connection in the sockets
-rwxr-xr-xsocket_conn.py12
-rwxr-xr-xsocketserver.py4
2 files changed, 12 insertions, 4 deletions
diff --git a/socket_conn.py b/socket_conn.py
index 433cc75..4367240 100755
--- a/socket_conn.py
+++ b/socket_conn.py
@@ -6,6 +6,7 @@
import socket
from zope import interface
import errno
+import select
from interfaces import endpoint
@@ -25,15 +26,22 @@ class SocketConnection(object):
""" 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 """
+ # check the socket for reading in non-blocking mode
+ read_socket, _, _ = select.select([self.s], [], [], 0.0)
+ if read_socket == []: return
try:
- return self.s.recv(1024)
+ recv = self.s.recv(1024)
+ if recv == b"":
+ # We should be able to read something, but got nothing.
+ # Reset the socket
+ raise RuntimeError("socket connection broken")
+ return recv
except socket.error as e:
err = e.args[0]
if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
diff --git a/socketserver.py b/socketserver.py
index 471b8be..0a7e9d4 100755
--- a/socketserver.py
+++ b/socketserver.py
@@ -104,12 +104,12 @@ class Handler(object):
def _read(self:object, conn:socket, mask:int):
""" Internal method used to retreive data from the socket
"""
- data = conn.recv(1024).strip()
+ data = conn.recv(1024)
if data == bytes("", "ascii"):
# A socket ready but sending garbage is a dead socket.
self.close(conn)
return
- json_data = str(data, "utf-8")
+ json_data = str(data.strip(), "utf-8")
try:
js = json.loads(json_data)
for key in js.keys():