Class: Wtails::WebSocket::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/wtails/web_socket.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, port) ⇒ Server

Returns a new instance of Server.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/wtails/web_socket.rb', line 20

def initialize(file, port)
  @file = file
  @port = port
  @logs = []
  @channel = Wtails.channel(file)
  @channel.subscribe do |msg|
    @logs << msg
    @logs.shift if @logs.size > LOG_SIZE
  end

  opts = {:host => "0.0.0.0", :port => port}
  s = ::WebSocket::EventMachine::Server.start(opts) do |socket|
    socket.onopen(&onopen(socket))
    socket.onmessage(&onmessage)
    socket.onerror(&onerror)
  end

  def onopen(socket)
    proc do
      send_message = proc do |message|
        next unless message
        str = message.respond_to?(:force_encoding) ?
        message.force_encoding("UTF-8") :
          message

        socket.send(str)
      end

      @logs.each(&send_message)
      id = @channel.subscribe(&send_message)

      socket.onclose do
        @channel.unsubscribe(id)
      end
    end
  end

  def onmessage
    proc do |message|
      @channel << message
    end
  end

  def onerror
    proc do |error|
      puts error
    end
  end
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file.



71
72
73
# File 'lib/wtails/web_socket.rb', line 71

def file
  @file
end

#portObject (readonly)

Returns the value of attribute port.



70
71
72
# File 'lib/wtails/web_socket.rb', line 70

def port
  @port
end

Instance Method Details

#onerrorObject



63
64
65
66
67
# File 'lib/wtails/web_socket.rb', line 63

def onerror
  proc do |error|
    puts error
  end
end

#onmessageObject



57
58
59
60
61
# File 'lib/wtails/web_socket.rb', line 57

def onmessage
  proc do |message|
    @channel << message
  end
end

#onopen(socket) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/wtails/web_socket.rb', line 37

def onopen(socket)
  proc do
    send_message = proc do |message|
      next unless message
      str = message.respond_to?(:force_encoding) ?
      message.force_encoding("UTF-8") :
        message

      socket.send(str)
    end

    @logs.each(&send_message)
    id = @channel.subscribe(&send_message)

    socket.onclose do
      @channel.unsubscribe(id)
    end
  end
end