Class: OPQ::WsServer

Inherits:
Object
  • Object
show all
Defined in:
lib/opqr/wsserver.rb

Instance Method Summary collapse

Constructor Details

#initialize(observer) ⇒ WsServer

Returns a new instance of WsServer.



7
8
9
10
# File 'lib/opqr/wsserver.rb', line 7

def initialize(observer)
  @observer = observer
  self.start
end

Instance Method Details

#startObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/opqr/wsserver.rb', line 11

def start
  EM.run {
    ws = Faye::WebSocket::Client.new('ws://'+$api_url.to_s+':'+$http_port.to_s+'/ws')
    ws.on :open do |event|
      puts "[WS] 连接已建立"
    end

    ws.on :message do |event|
      puts "[WS] 收到数据-->".force_encoding('UTF-8')+ "#{event.data}".force_encoding('UTF-8')
      @observer.on_message_received(event.data)
    end

    ws.on :close do |event|
      puts "[WS] 连接已断开"
      ws = nil
    end
  }
    # EM.run do

    #   WebSocket::EventMachine::Server.start(:host => "0.0.0.0", :port => @port, :mode => :async) do |ws|

    #     ws.onopen do

    #       puts "[WS] 连接已建立"

    #     end

    #     ws.onmessage do |msg, type|

    #       puts "[WS] 收到数据-->".force_encoding('UTF-8')+ "#{msg}".force_encoding('UTF-8')

    #       @observer.on_message_received(msg)

    #     end

    #

    #     ws.onclose do

    #       puts "[WS] 连接已断开"

    #     end

    #   end

    # end

end