Class: WampClient::Transport::WebSocketTransport

Inherits:
Base
  • Object
show all
Defined in:
lib/wamp_client/transport.rb

Overview

This implementation uses the ‘websocket-eventmachine-client’ Gem. This is the default if no transport is included

Instance Attribute Summary collapse

Attributes inherited from Base

#connected, #headers, #protocol, #serializer, #type, #uri

Instance Method Summary collapse

Methods inherited from Base

#connected?, #on_close, #on_error, #on_message, #on_open

Constructor Details

#initialize(options) ⇒ WebSocketTransport

Returns a new instance of WebSocketTransport.



122
123
124
125
126
# File 'lib/wamp_client/transport.rb', line 122

def initialize(options)
  super(options)
  self.type = 'websocket'
  self.socket = nil
end

Instance Attribute Details

#socketObject

Returns the value of attribute socket.



120
121
122
# File 'lib/wamp_client/transport.rb', line 120

def socket
  @socket
end

Instance Method Details

#connectObject



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/wamp_client/transport.rb', line 128

def connect
  self.socket = WebSocket::EventMachine::Client.connect(
      :uri => self.uri,
      :headers => self.headers
  )

  self.socket.onopen do
    self.connected = true
    @on_open.call unless @on_open.nil?
  end

  self.socket.onmessage do |msg, type|
    @on_message.call(self.serializer.deserialize(msg)) unless @on_message.nil?
  end

  self.socket.onclose do |code, reason|
    self.connected = false
    @on_close.call(reason) unless @on_close.nil?
  end
end

#disconnectObject



149
150
151
# File 'lib/wamp_client/transport.rb', line 149

def disconnect
  self.connected = !self.socket.close  # close returns 'true' if the connection was closed immediately
end

#send_message(msg) ⇒ Object



153
154
155
156
157
158
159
# File 'lib/wamp_client/transport.rb', line 153

def send_message(msg)
  if self.connected
    self.socket.send(self.serializer.serialize(msg), {type: 'text'})
  else
    raise RuntimeError, "Socket must be open to call 'send_message'"
  end
end

#timer(milliseconds, &callback) ⇒ Object



161
162
163
164
165
166
# File 'lib/wamp_client/transport.rb', line 161

def timer(milliseconds, &callback)
  delay = (milliseconds.to_f/1000.0).ceil
  EM.add_timer(delay) {
    callback.call
  }
end