Created
May 11, 2010 01:10
-
-
Save martinisoft/396782 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
require 'eventmachine' | |
module EventMachine | |
module Protocols | |
class SRCDS < Connection | |
include EventMachine::Deferrable | |
def initialize | |
@authed = false | |
@commands = { "exec" => 2, "auth" => 3 } | |
@responses = { "auth" => 2, "normal" => 0 } | |
@nullbyte = "\x00" | |
@request_id = 0 | |
end | |
def post_init | |
@start_time = Time.now | |
end | |
def connection_completed | |
@completed = true | |
set_deferred_status :succeeded, (Time.now - @start_time) | |
puts "Connected to server" | |
# close_connection | |
end | |
def receive_data data | |
puts "> #{data}" | |
# string1 = "" | |
# string2 = "" | |
# expected = true | |
# while(expected) | |
# # @log.debug("Reading size") | |
# # read 4 bytes from packet | |
# rawsize = @socket.recv(4) | |
# # get packet size | |
# psize = rawsize.unpack("V").shift | |
# # @log.debug("psize = #{psize.inspect}") | |
# # read the rest of the packet | |
# raw = @socket.recv(psize) | |
# # @log.debug("Received (size: #{psize}):\n#{raw.inspect}") | |
# # VVAA - request, command, string, string | |
# request_id, command, str1, str2 = raw.unpack("VVA*A*") | |
# string1 += str1.chomp | |
# string2 += str2.chomp | |
# # if the size was bigger than 4096, look for another packet | |
# expected = false unless (psize >= 4096) | |
# # @log.debug("Multiple packets: #{expected}") | |
# end | |
# return {:request_id => request_id, :command => command, :string1 => string1, :string2 => string2} | |
end | |
def send_packet(command, str1, str2="") | |
if authed? | |
@request_id += 1 | |
packet = str1 + @nullbyte + str2 + @nullbyte | |
packet = [@request_id, command].pack("VV") + packet | |
packet = [packet.length].pack("V") + packet | |
# @log.debug("Sending packet: [#{packet.inspect}]") | |
send_data packet | |
return @request_id | |
else | |
raise "Not connected or authenticated" | |
end | |
end | |
def unbind | |
set_deferred_status :failed, (Time.now - @start_time) unless @completed | |
puts "Connection closed..." | |
end | |
def authed? | |
@authed ||= false | |
end | |
end | |
end | |
end | |
module MyKeyboardHandler | |
include EM::Protocols::LineText2 | |
def receive_line data | |
if data =~ /exit/ | |
puts "Exiting..." | |
EventMachine.stop | |
else | |
puts ">> #{data}" | |
end | |
end | |
end | |
EM.run { | |
EM.connect "localhost", 27015, EM::P::SRCDS | |
EM.open_keyboard(MyKeyboardHandler) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment