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.



115
116
117
118
119
# File 'lib/wamp_client/transport.rb', line 115

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

Instance Attribute Details

#socketObject

Returns the value of attribute socket.



113
114
115
# File 'lib/wamp_client/transport.rb', line 113

def socket
  @socket
end

Instance Method Details

#connectObject



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/wamp_client/transport.rb', line 121

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



142
143
144
# File 'lib/wamp_client/transport.rb', line 142

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

#send_message(msg) ⇒ Object



146
147
148
149
150
151
152
# File 'lib/wamp_client/transport.rb', line 146

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