Class: Browser::Socket

Inherits:
Object show all
Includes:
Event::Target, IO::Writable, Native
Defined in:
opal/browser/socket.rb

Overview

A Socket allows the browser and a server to have a bidirectional data connection.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Event::Target

#off, #on, #on!, #trigger, #trigger!

Constructor Details

#initialize(url, protocol = nil) { ... } ⇒ Socket

Create a connection to the given URL, optionally using the given protocol.

Yields:

  • if the block has no parameters it's instance_execd, otherwise it's called with self


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'opal/browser/socket.rb', line 27

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

Instance Attribute Details

#bufferedInteger (readonly)


53
# File 'opal/browser/socket.rb', line 53

alias_native :buffered, :bufferedAmount

#extensionsArray<String> (readonly)


94
95
96
# File 'opal/browser/socket.rb', line 94

def extensions
  `#@native.extensions`.split(/\s*,\s*/)
end

#protocolString (readonly)


45
# File 'opal/browser/socket.rb', line 45

alias_native :protocol

#state:connecting, ... (readonly)


74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'opal/browser/socket.rb', line 74

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

#type:blob, ... (readonly)


57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'opal/browser/socket.rb', line 57

def type
  %x{
    switch (#@native.binaryType) {
      case "blob":
        return "blob";

      case "arraybuffer":
        return "buffer";

      default:
        return "string";
    }
  }
end

#urlString (readonly)


49
# File 'opal/browser/socket.rb', line 49

alias_native :url

Class Method Details

.supported?Boolean


8
9
10
# File 'opal/browser/socket.rb', line 8

def self.supported?
  Browser.supports? :WebSocket
end

Instance Method Details

#alive?Boolean

Check if the socket is alive.


99
100
101
# File 'opal/browser/socket.rb', line 99

def alive?
  state == :open
end

#close(code = nil, reason = nil) ⇒ Object

Close the socket.


118
119
120
# File 'opal/browser/socket.rb', line 118

def close(code = nil, reason = nil)
  `#@native.close(#{code.to_n}, #{reason.to_n})`
end

#write(data) ⇒ Object Also known as: <<, send

Send data to the socket.


106
107
108
# File 'opal/browser/socket.rb', line 106

def write(data)
  `#@native.send(#{data.to_n})`
end