Class: PusherClient::PusherWebSocket

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

Constant Summary collapse

WAIT_EXCEPTIONS =
[Errno::EAGAIN, Errno::EWOULDBLOCK]
CA_FILE =
File.expand_path('../../../certs/cacert.pem', __FILE__)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of PusherWebSocket


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
50
51
52
53
# File 'lib/pusher-client/websocket.rb', line 14

def initialize(url, params = {})
  @hs ||= WebSocket::Handshake::Client.new(:url => url)
  @frame ||= WebSocket::Frame::Incoming::Server.new(:version => @hs.version)
  @socket = TCPSocket.new(@hs.host, @hs.port || 80)
  @cert_file = params[:cert_file]
  @logger = params[:logger] || PusherClient.logger

  if params[:ssl] == true
    ctx = OpenSSL::SSL::SSLContext.new
    if params[:ssl_verify]
      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 = @cert_file || CA_FILE
    else
      ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end

    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?

    @hs << data

    if @hs.finished?
      raise @hs.error.to_s unless @hs.valid?
      @handshaked = true
      break
    end
  end
end

Instance Attribute Details

#socketObject

Returns the value of attribute socket


12
13
14
# File 'lib/pusher-client/websocket.rb', line 12

def socket
  @socket
end

Instance Method Details

#closeObject


89
90
91
92
93
# File 'lib/pusher-client/websocket.rb', line 89

def close
  @socket.close
rescue IOError => error
  logger.debug error.message
end

#receiveObject


67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/pusher-client/websocket.rb', line 67

def receive
  raise "no handshake!" unless @handshaked

  begin
    data = @socket.read_nonblock(1024)
  rescue *WAIT_EXCEPTIONS
    IO.select([@socket])
    retry
  end
  @frame << data

  messages = []
  while message = @frame.next
    if message.type === :ping
      send(message.data, :pong)
      return messages
    end
    messages << message.to_s
  end
  messages
end

#send(data, type = :text) ⇒ Object


55
56
57
58
59
60
61
62
63
64
65
# File 'lib/pusher-client/websocket.rb', line 55

def send(data, type = :text)
  raise "no handshake!" unless @handshaked

  data = WebSocket::Frame::Outgoing::Client.new(
    :version => @hs.version,
    :data => data,
    :type => type
  ).to_s
  @socket.write data
  @socket.flush
end