Class: PusherClient::WebSocket

Inherits:
Object
  • Object
show all
Defined in:
lib/pusher-client/websocket.rb

Instance Method Summary collapse

Constructor Details

#initialize(url, params = {}) ⇒ WebSocket

Returns a new instance of WebSocket.



9
10
11
12
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
# File 'lib/pusher-client/websocket.rb', line 9

def initialize(url, params = {})
  @hs ||= LibWebSocket::OpeningHandshake::Client.new(:url => url, :version => params[:version])
  @frame ||= LibWebSocket::Frame.new

  @socket = TCPSocket.new(@hs.url.host, @hs.url.port || 80)

  if params[:ssl] == true

    ctx = OpenSSL::SSL::SSLContext.new
    ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
    # http://curl.haxx.se/ca/cacert.pem
    ctx.ca_file = path_to_cert()

    ssl_sock = OpenSSL::SSL::SSLSocket.new(@socket, ctx)
    ssl_sock.sync_close = true
    ssl_sock.connect

    @socket = ssl_sock

  end

  @socket.write(@hs.to_s)
  @socket.flush

  loop do
    data = @socket.getc
    next if data.nil?

    result = @hs.parse(data.chr)

    raise @hs.error unless result

    if @hs.done?
      @handshaked = true
      break
    end
  end
end

Instance Method Details

#closeObject



77
78
79
# File 'lib/pusher-client/websocket.rb', line 77

def close
  @socket.close
end

#path_to_certObject



48
49
50
# File 'lib/pusher-client/websocket.rb', line 48

def path_to_cert
  File.join(File.dirname(File.expand_path(__FILE__)), '../../certs/cacert.pem')
end

#receiveObject



60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/pusher-client/websocket.rb', line 60

def receive
  raise "no handshake!" unless @handshaked

  data = @socket.gets("\xff")
  @frame.append(data)

  messages = []
  while message = @frame.next
    messages << message
  end
  messages
end

#send(data) ⇒ Object



52
53
54
55
56
57
58
# File 'lib/pusher-client/websocket.rb', line 52

def send(data)
  raise "no handshake!" unless @handshaked

  data = @frame.new(data).to_s
  @socket.write data
  @socket.flush
end

#socketObject



73
74
75
# File 'lib/pusher-client/websocket.rb', line 73

def socket
  @socket
end