Class: Rmpd::Connection

Inherits:
Object
  • Object
show all
Includes:
Commands, Socket::Constants
Defined in:
lib/rmpd/connection.rb

Constant Summary collapse

MAX_RETRIES =
5

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Commands

#kill, #volume

Constructor Details

#initialize(config_file = nil) ⇒ Connection

Returns a new instance of Connection.



16
17
18
19
20
# File 'lib/rmpd/connection.rb', line 16

def initialize(config_file=nil)
  @config = Rmpd::Config.new(config_file)
  @socket = nil
  @socket_mu = Mutex.new
end

Instance Attribute Details

#socketObject (readonly)

Returns the value of attribute socket.



13
14
15
# File 'lib/rmpd/connection.rb', line 13

def socket
  @socket
end

Instance Method Details

#closeObject



22
23
24
# File 'lib/rmpd/connection.rb', line 22

def close
  @socket_mu.synchronize {@socket.close}
end

#connectObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rmpd/connection.rb', line 30

def connect
  @socket_mu.lock
  begin
    return unless @socket.nil? || @socket.closed?

    if %r{^/} === @config.hostname
      connect_unix_socket
    else
      connect_inet_socket
    end

    read_response # protocol version, ignore for now
    if @config.password
      send_command("password", @config.password)
      Response.factory("password").parse(read_response)
    end
  ensure
    @socket_mu.unlock
  end
end

#read_responseObject



51
52
53
54
55
56
57
58
59
60
# File 'lib/rmpd/connection.rb', line 51

def read_response
  response = []

  while (line = @socket.readline.force_encoding("UTF-8"))
    response << line.strip
    break if END_RE === line
  end

  response
end

#send_command(command, *args) ⇒ Object



62
63
64
65
66
67
# File 'lib/rmpd/connection.rb', line 62

def send_command(command, *args)
  @socket.puts("#{command} #{quote(args).join(" ")}".strip)
rescue Errno::EPIPE, EOFError => e
  @socket.close
  raise MpdDisconnectedError.new(e)
end

#synchronize(&block) ⇒ Object



26
27
28
# File 'lib/rmpd/connection.rb', line 26

def synchronize(&block)
  @socket_mu.synchronize(&block)
end