Permalink
Browse files

Add optional connection timeout parameter

  • Loading branch information...
1 parent 746cdb8 commit 39047acf1c9af21cc39566365b4a759faa54c8be Michael Helmling committed with Mar 30, 2012
Showing with 12 additions and 5 deletions.
  1. +7 −5 mpd.py
  2. +5 −0 test.py
View
@@ -378,15 +378,16 @@ def _reset(self):
self._rfile = _NotConnected()
self._wfile = _NotConnected()
- def _connect_unix(self, path):
+ def _connect_unix(self, path, timeout):
if not hasattr(socket, "AF_UNIX"):
raise ConnectionError("Unix domain sockets not supported "
"on this platform")
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ sock.settimeout(timeout)
sock.connect(path)
return sock
- def _connect_tcp(self, host, port):
+ def _connect_tcp(self, host, port, timeout):
try:
flags = socket.AI_ADDRCONFIG
except AttributeError:
@@ -400,6 +401,7 @@ def _connect_tcp(self, host, port):
try:
sock = socket.socket(af, socktype, proto)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
+ sock.settimeout(timeout)
sock.connect(sa)
return sock
except socket.error as e:
@@ -411,13 +413,13 @@ def _connect_tcp(self, host, port):
else:
raise ConnectionError("getaddrinfo returns an empty list")
- def connect(self, host, port):
+ def connect(self, host, port, timeout=None):
if self._sock is not None:
raise ConnectionError("Already connected")
if host.startswith("/"):
- self._sock = self._connect_unix(host)
+ self._sock = self._connect_unix(host, timeout)
else:
- self._sock = self._connect_tcp(host, port)
+ self._sock = self._connect_tcp(host, port, timeout)
self._rfile = self._sock.makefile("r")
self._wfile = self._sock.makefile("w")
try:
View
@@ -197,5 +197,10 @@ def test_unicode_as_reponse(self):
def test_numbers_as_command_args(self):
res = self.client.find("file", 1)
+ def test_timeout(self):
+ self.client.disconnect()
+ self.client.connect(TEST_MPD_HOST, TEST_MPD_PORT, timeout=5)
+ self.assertEqual(self.client._sock.gettimeout(), 5)
+
if __name__ == '__main__':
unittest.main()

0 comments on commit 39047ac

Please sign in to comment.