Class: Async::WebSocket::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/async/websocket/client.rb

Overview

This is a basic synchronous websocket client:

Constant Summary collapse

EVENTS =
[:open, :message, :close]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(socket, url: "ws://.") ⇒ Client

Returns a new instance of Client.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/async/websocket/client.rb', line 30

def initialize(socket, url: "ws://.")
  @socket = socket
  @url = url
  
  @driver = ::WebSocket::Driver.client(self)
  
  @queue = []
  
  @driver.on(:error) do |error|
    raise error
  end
  
  EVENTS.each do |event|
    @driver.on(event) do |data|
      @queue.push(data)
    end
  end
  
  @driver.start
end

Instance Attribute Details

#driverObject (readonly)

Returns the value of attribute driver.



51
52
53
# File 'lib/async/websocket/client.rb', line 51

def driver
  @driver
end

#urlObject (readonly)

Returns the value of attribute url.



52
53
54
# File 'lib/async/websocket/client.rb', line 52

def url
  @url
end

Instance Method Details

#closeObject



84
85
86
# File 'lib/async/websocket/client.rb', line 84

def close
  @driver.close
end

#next_eventObject



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/async/websocket/client.rb', line 54

def next_event
  while @queue.empty?
    data = @socket.read(1024)
    
    if data and !data.empty?
      @driver.parse(data)
    else
      return nil
    end
  end
  
  @queue.shift
rescue EOFError
  return nil
end

#next_messageObject



70
71
72
73
74
75
76
77
78
# File 'lib/async/websocket/client.rb', line 70

def next_message
  while event = next_event
    if event.is_a? ::WebSocket::Driver::MessageEvent
      return JSON.parse(event.data)
    elsif event.is_a? ::WebSocket::Driver::CloseEvent
      return nil
    end
  end
end

#write(data) ⇒ Object



80
81
82
# File 'lib/async/websocket/client.rb', line 80

def write(data)
  @socket.write(data)
end