Commit 131c55d878f3ea33b30b78a474101440529286e7

Anton Maminov 2014-12-06T18:00:56

Merge pull request #4 from pizzocel/automatic-reconnection Automatic reconnect after the server dropped the connection.

diff --git a/lib/mpd_client.rb b/lib/mpd_client.rb
index 0f8c0f3..962fa42 100644
--- a/lib/mpd_client.rb
+++ b/lib/mpd_client.rb
@@ -159,12 +159,18 @@ class MPDClient
   end
 
   def connect(host = 'localhost', port = 6600)
-    log.info("MPD connect #{host}, #{port}") if log
-    if host.start_with?('/')
-      @socket = UNIXSocket.new(host)
+    @host = host
+    @port = port
+    reconnect
+  end
+
+  def reconnect
+    log.info("MPD (re)connect #{host}, #{port}") if log
+    if @host.start_with?('/')
+      @socket = UNIXSocket.new(@host)
       hello
     else
-      @socket = TCPSocket.new(host, port)
+      @socket = TCPSocket.new(@host, @port)
       hello
     end
   end
@@ -216,7 +222,12 @@ class MPDClient
   end
 
   def write_line(line)
-    @socket.puts line
+    begin
+      @socket.puts line
+    rescue Errno::EPIPE
+      reconnect
+      @socket.puts line
+    end
     @socket.flush
   end