Download: ruby-orbited.rb

File ruby-orbited.rb, 1.6 kB (added by frank, 6 months ago)
Line 
1require 'socket'
2include Socket::Constants
3require 'json'
4
5BUFFER_SIZE = 4096
6LINE_END = "\r\n"
7
8module SimpleOrbit
9end
10
11class SimpleOrbit::Client
12  @@version = 'Orbit 1.0'
13  def initialize(addr, port)
14    @addr = addr
15    @port = port
16    @socket = nil
17    @id = 0
18    @connected = false
19  end
20  def connect()
21    @connected = true
22    if @socket
23      # already connected
24      return
25    end
26    @socket = TCPSocket.new(@addr, @port)
27  end
28  def disconnect()
29    if @connected
30      @connected = false
31      @socket.close()
32      @socket = nil
33    end
34  end
35  def reconnect()
36    disconnect()
37    connect()
38  end
39  def sendline(line='')
40    @socket.write(line.to_s + LINE_END)
41    puts line.to_s
42  end
43  def event(recipients, body, json=true, try_again=true)
44    if not @connected
45      connect()
46    end
47    begin
48      if json
49        body = JSON.generate(body)
50      end
51      if not @socket
52        raise ## **Connection-lost**
53      end
54      begin
55        @id = @id + 1
56        sendline(@@version.to_s)
57        sendline('Event')
58        sendline('id: ' + @id.to_s)
59        for recipient in recipients
60          sendline('recipient: ' + recipient.to_s)
61        end
62        sendline('length: ' + body.length.to_s)
63        sendline()
64        @socket.write(body)
65        puts body.to_s
66        return read_response()
67      rescue
68        disconnect()
69        raise
70      end
71    rescue
72      if try_again
73          reconnect()
74          event(recipients, body, json, false)
75      else
76          raise
77      end
78    end
79  end
80  def read_response()
81    # FIXME: this is incorrect. Should read until it gets a \r\n\r\n
82    return @socket.read(15)
83  end
84end