-
-
Save jsn/b9186dd2e9ce5b3d5eac40fd56163ade to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def make_ws url, method | |
ws = WebSocket::Client::Simple.connect url | |
u1 = "ws(#{url.split(WS_BASE).last})" | |
now = 0 | |
prg = 0 | |
sf = self | |
ws.on :open do | |
sf.debug "*** #{u1} connected" | |
now = 0 | |
if sf.wss[url] && sf.wss[url] != ws | |
sf.debug "*** #{u1} replacing old socket" | |
old = sf.wss[url] | |
sf.wss[url] = ws | |
old.close rescue nil | |
end | |
end | |
ws.on :error do |e| | |
sf.debug "*** #{u1} error: #{e}" | |
end | |
ws.on :close do |e| | |
sf.debug "*** #{u1} close: #{e}" if sf.wss[url] == self | |
end | |
ws.on :message do |msg| | |
case msg.type | |
when :ping | |
now += 1 | |
sf.debug "> #{u1} (ping #{now})" | |
ws.send msg.data, type: :pong | |
if now >= 4 | |
sf.debug "*** #{u1} reconnecting" | |
sf.make_ws url, method | |
end | |
when :text | |
now = 0 | |
if sf.options[:debug] | |
STDERR.print "#{PROGRESS[prg % PROGRESS.size]}\x08" | |
prg += 1 | |
end | |
ws.emit :data, JSON.load(msg.data) | |
end | |
end | |
ws.on :data do |data| | |
if data['ok'] | |
sf.send method, data | |
else | |
sf.debug "> #{u1} NOT OK: #{data}" | |
end | |
end | |
ws | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment