Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Fix #61 freeze/broken pipe after some idle time
Browse files Browse the repository at this point in the history
When keeping long-lived websocket connection, after some idle time
the connection will go into a bad state. Calling send() cause no
response at first and then broken pipe error is raised on the
subsequent call. The cause is that there is no designated thread
to keep the socket alive.
  • Loading branch information
ejel committed Jun 22, 2018
1 parent 31d499b commit 47d3aa6
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions samsungctl/remote_websocket.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import base64
import json
import logging
import socket

This comment has been minimized.

Copy link
@ejel

ejel Jun 23, 2018

Author

This was unused.

import threading
import time
import select

from . import exceptions

Expand All @@ -26,9 +27,12 @@ def __init__(self, config):
self._serialize_string(config["name"]))

self.connection = websocket.create_connection(url, config["timeout"])

self._read_response()

## Keep long-lived connection alive by spawning a thread
thread = threading.Thread(target=self._keep_alive, daemon=True)
thread.start()

def __enter__(self):
return self

Expand Down Expand Up @@ -73,6 +77,18 @@ def _read_response(self):

logging.debug("Access granted.")

def _keep_alive(self):
while True:
r, w, e = select.select((self.connection.sock, ), (), ())
if not (self.connection and self.connection.connected):
# stop if connection was already closed
# while blocking in select function above
logging.debug("keep alive thread terminating.")
return
if r:
_ = self.connection.recv()
logging.debug("data received.")

@staticmethod
def _serialize_string(string):
if isinstance(string, str):
Expand Down

0 comments on commit 47d3aa6

Please sign in to comment.