Skip to content

Instantly share code, notes, and snippets.

@glurp
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save glurp/93b3a11e0fdc90120ba4 to your computer and use it in GitHub Desktop.

Select an option

Save glurp/93b3a11e0fdc90120ba4 to your computer and use it in GitHub Desktop.
simple TCP client connection
# GClient.rb
#
require 'thread'
require 'socket'
require 'timeout'
BasicSocket.do_not_reverse_lookup = true
Thread.abort_on_exception = true
class GClient
def self.run_continous(host,port,timer_interconnection,&b)
Thread.new do
loop { (run_one_shot(host,port,&b)||Thread.new {}).join ; sleep timer_interconnection }
end
end
def self.run_one_shot(host="localhost",port=80)
puts "Connecting to #{host}:#{port}..."
begin
socket = TCPSocket.new(host,port)
rescue
puts "not connected ro #{host}:#{port}: " + $!.to_s
return nil
end
Thread.new do
begin
yield(socket)
rescue Exception => e
puts "#{e}\n #{e.backtrace.join("\n ")}"
ensure
socket.close() rescue nil
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment