Skip to content

Instantly share code, notes, and snippets.

@snuxoll
Created March 18, 2009 10:59
Show Gist options
  • Save snuxoll/81061 to your computer and use it in GitHub Desktop.
Save snuxoll/81061 to your computer and use it in GitHub Desktop.
require 'ruby-event'
# General purpose wrapper for network connections
class NetworkConnection
attr_reader :hostname, :port, :thread
# Create a new event to be fired when we recieve data
# from the server
event :data_received
# Creates a new instance of NetworkConnection with the
# specified hostname and port
def initialize(hostname, port)
@hostname = hostname
@port = port
end
# Connects to the specified hostname and port given in new
def connect
@thread = Thread.new do
@socket = TCPSocket.new(@hostname, @port)
@socket.each { |line| data_received(line) }
end
end
# Closes the socket
def disconnect
@socket.close
end
# Sends text to the socket
def send(text)
@socket.send(text + '\r\n', 0)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment