class Hyperstack::Hotloader::Socket
Code taken from opal browser, did not want to force an opal-browser dependency
A {Socket} allows the browser and a server to have a bidirectional data connection.
Public Class Methods
Create a connection to the given URL, optionally using the given protocol.
@param url [String] the URL to connect to @param protocol [String] the protocol to use
@yield if the block has no parameters it's `instance_exec`d, otherwise it's
called with `self`
# File lib/hyperstack/hotloader/socket.rb, line 43 def initialize(url, protocol = nil, &block) if native?(url) super(url) elsif protocol super(`new window.WebSocket(#{url.to_s}, #{protocol.to_n})`) else super(`new window.WebSocket(#{url.to_s})`) end if block.arity == 0 instance_exec(&block) else block.call(self) end if block end
# File lib/hyperstack/hotloader/socket.rb, line 15 def self.supported? Browser.supports? :WebSocket end
Public Instance Methods
Check if the socket is alive.
# File lib/hyperstack/hotloader/socket.rb, line 115 def alive? state == :open end
Close the socket.
@param code [Integer, nil] the error code @param reason [String, nil] the reason for closing
# File lib/hyperstack/hotloader/socket.rb, line 130 def close(code = nil, reason = nil) `#@native.close(#{code.to_n}, #{reason.to_n})` end
@!attribute [r] extensions @return [Array<String>] the extensions used by the socket
# File lib/hyperstack/hotloader/socket.rb, line 110 def extensions `#@native.extensions`.split(/\s*,\s*/) end
# File lib/hyperstack/hotloader/socket.rb, line 22 def on(str, &block) puts "putting #{str}" b = block cmd = "foo.on#{str} = #{b}" puts cmd `#{cmd}` # `foo.on#{str} = #{b}` end
@!attribute [r] state @return [:connecting, :open, :closing, :closed] the state of the socket
# File lib/hyperstack/hotloader/socket.rb, line 90 def state %x{ switch (#@native.readyState) { case window.WebSocket.CONNECTING: return "connecting"; case window.WebSocket.OPEN: return "open"; case window.WebSocket.CLOSING: return "closing"; case window.WebSocket.CLOSED: return "closed"; } } end
@!attribute [r] type @return [:blob, :buffer, :string] the type of the socket
# File lib/hyperstack/hotloader/socket.rb, line 73 def type %x{ switch (#@native.binaryType) { case "blob": return "blob"; case "arraybuffer": return "buffer"; default: return "string"; } } end
Send data to the socket.
@param data [#to_n] the data to send
# File lib/hyperstack/hotloader/socket.rb, line 122 def write(data) `#@native.send(#{data.to_n})` end