Class: Minecraft::RToolkit::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/minecraft_rtoolkit/connection.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Connection

Returns a new instance of Connection.



4
5
6
7
8
9
10
11
12
13
# File 'lib/minecraft_rtoolkit/connection.rb', line 4

def initialize(options={})
    @user = options[:user]
    @password = options[:password]
    @host = options[:host]
    @port = options[:port]
    @connection = nil

    #define destructor
    ObjectSpace.define_finalizer(self, method(:close))
end

Instance Method Details

#closeObject



54
55
56
57
58
# File 'lib/minecraft_rtoolkit/connection.rb', line 54

def close
    unless @connection.nil?
        @connection.close
    end
end

#make_request(action) ⇒ Object



15
16
17
# File 'lib/minecraft_rtoolkit/connection.rb', line 15

def make_request(action)
    "#{action.upcase}:#{@user}:#{@password}"
end

#openObject



19
20
21
22
23
24
# File 'lib/minecraft_rtoolkit/connection.rb', line 19

def open
    if @connection.nil?
        @connection = UDPSocket.new()
        @connection.connect(@host, @port)
    end
end

#recieveObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/minecraft_rtoolkit/connection.rb', line 38

def recieve
    unless @connection.nil?
        begin
            response = @connection.recvfrom(32)
            case response[0]
            when 'response:success' then true
            when /^response:.*/ then false
            else
                response [0]
            end
        rescue
            raise SocketError
        end
    end
end

#send(action) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/minecraft_rtoolkit/connection.rb', line 26

def send(action)
    open if @connection.nil?
    unless @connection.nil?
        begin
            @connection.send(make_request(action), 0)
            recieve
        rescue
            raise SocketError
        end
    end
end