Class: Async::WebSocket::Connection

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

Overview

This is a basic synchronous websocket client:

Direct Known Subclasses

Client, Server

Constant Summary collapse

BLOCK_SIZE =
Async::IO::Stream::BLOCK_SIZE
EVENTS =
[:open, :message, :close]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(socket, driver) ⇒ Connection

Returns a new instance of Connection.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/async/websocket/connection.rb', line 34

def initialize(socket, driver)
  @socket = socket
  @driver = driver
  
  @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.



53
54
55
# File 'lib/async/websocket/connection.rb', line 53

def driver
  @driver
end

#urlObject (readonly)

Returns the value of attribute url.



54
55
56
# File 'lib/async/websocket/connection.rb', line 54

def url
  @url
end

Instance Method Details

#closeObject



96
97
98
99
# File 'lib/async/websocket/connection.rb', line 96

def close
  @driver.close
  @socket.close
end

#next_eventObject



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/async/websocket/connection.rb', line 56

def next_event
  @socket.flush
  
  while @queue.empty?
    data = @socket.readpartial(BLOCK_SIZE)
    
    if data and !data.empty?
      @driver.parse(data)
    else
      return nil
    end
  end
  
  @queue.shift
rescue EOFError, Errno::ECONNRESET
  return nil
end

#next_messageObject



74
75
76
77
78
79
80
81
82
# File 'lib/async/websocket/connection.rb', line 74

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

#send_message(message) ⇒ Object



88
89
90
# File 'lib/async/websocket/connection.rb', line 88

def send_message(message)
  @driver.text(JSON.dump(message))
end

#send_text(text) ⇒ Object



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

def send_text(text)
  @driver.text(text)
end

#write(data) ⇒ Object



92
93
94
# File 'lib/async/websocket/connection.rb', line 92

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