Skip to content

Commit

Permalink
Reconnect if client closes connection
Browse files Browse the repository at this point in the history
  • Loading branch information
bendangelo committed Nov 19, 2023
1 parent 1a24b2b commit 2f97e0b
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions lib/sonic/connection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def initialize(host, port, channel_type, password = nil)
end

def connect
read # ...
socket.gets # ...
write(['START', @channel_type, @password].compact.join(' '))
read.start_with?('STARTED ')
end
Expand All @@ -23,20 +23,36 @@ def disconnect
end

def read
data = socket.gets.chomp
data = socket.gets&.chomp

raise ServerError, data if data.nil?
raise ServerError, data if data.start_with?('ENDED ')
raise ServerError, data if data.start_with?('ERR ')

data
end

def write(data)
socket.puts(data)
begin
socket.puts(data)
rescue Errno::EPIPE
reconnect
socket.puts(data)
end
end


private

def socket
@socket ||= TCPSocket.open(@host, @port)
end

def reconnect
@socket.close if @socket
@socket = TCPSocket.open(@host, @port)

connect
end
end
end

0 comments on commit 2f97e0b

Please sign in to comment.