Class: WebSocket::Client::Simple::Client

Inherits:
Object
  • Object
show all
Includes:
EventEmitter
Defined in:
lib/websocket-client-simple/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url) ⇒ Client

Returns a new instance of Client.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/websocket-client-simple/client.rb', line 13

def initialize(url)
  @url = url
  uri = URI.parse url
  @socket = TCPSocket.new(uri.host, uri.port || 80)
  @hs = ::WebSocket::Handshake::Client.new :url => url
  @handshaked = false
  frame = ::WebSocket::Frame::Incoming::Client.new
  @closed = false
  once :__close do |err|
    close
    emit :close, err
  end

  @thread = Thread.new do
    while !@closed do
      begin
        recv_data = @socket.getc
      rescue => e
        emit :__close, e
      end
      if !@handshaked
        @hs << recv_data
        if @hs.finished?
          @handshaked = true
          emit :open
        end
      else
        frame << recv_data
        while msg = frame.next
          emit :message, msg
        end
      end
    end
  end

  @socket.write @hs.to_s
end

Instance Attribute Details

#urlObject (readonly)

Returns the value of attribute url.



11
12
13
# File 'lib/websocket-client-simple/client.rb', line 11

def url
  @url
end

Instance Method Details

#closeObject



62
63
64
65
66
67
68
69
# File 'lib/websocket-client-simple/client.rb', line 62

def close
  return if @closed
  @closed = true
  @socket.close if @socket
  Thread.kill @thread if @thread
  @socket = nil
  emit :__close
end

#send(data, opt = {:type => :text}) ⇒ Object



51
52
53
54
55
56
57
58
59
60
# File 'lib/websocket-client-simple/client.rb', line 51

def send(data, opt={:type => :text})
  return if !@handshaked or @closed
  type = opt[:type]
  frame = ::WebSocket::Frame::Outgoing::Client.new(:data => data, :type => type, :version => @hs.version)
  begin
    @socket.write frame.to_s
  rescue => e
    emit :__close, e
  end
end