Class: Viaduct::WebPush::WebSocket::RawSocket

Inherits:
Object
  • Object
show all
Defined in:
lib/viaduct/web_push/web_socket/raw_socket.rb

Constant Summary collapse

WAIT_EXCEPTIONS =
[Errno::EWOULDBLOCK, Errno::EAGAIN, IO::WaitReadable]

Instance Method Summary collapse

Constructor Details

#initializeRawSocket

Open an SSL connection and perform the HTTP upgrade/websockets handhsake procedure

Raises:



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/viaduct/web_push/web_socket/raw_socket.rb', line 11

def initialize
  @handshake = ::WebSocket::Handshake::Client.new(:url => Viaduct::WebPush::WebSocket.endpoint)
  @connection = TCPSocket.new(@handshake.host, @handshake.port || 443)

  ssl_ctx = OpenSSL::SSL::SSLContext.new
  ssl_ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER
  ssl_ctx.cert_store = OpenSSL::SSL::SSLContext::DEFAULT_CERT_STORE

  ssl = OpenSSL::SSL::SSLSocket.new(@connection, ssl_ctx)
  ssl.sync_close = true
  ssl.connect

  @connection = ssl

  @connection.write @handshake.to_s
  @connection.flush

  while line = @connection.gets
    @handshake << line
    break if @handshake.finished?
  end

  raise HandshakeError unless @handshake.valid?
end

Instance Method Details

#disconnectObject

Close the connection



70
71
72
# File 'lib/viaduct/web_push/web_socket/raw_socket.rb', line 70

def disconnect
  @connection.close
end

#receiveObject

Read data from the socket and wait with IO#select



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/viaduct/web_push/web_socket/raw_socket.rb', line 48

def receive
  frame = ::WebSocket::Frame::Incoming::Server.new(:version => @handshake.version)

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

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

  messages
end

#send_data(message, type = :text) ⇒ Object

Send a websocket frame out on the connection



39
40
41
42
43
# File 'lib/viaduct/web_push/web_socket/raw_socket.rb', line 39

def send_data(message, type=:text)
  frame = ::WebSocket::Frame::Outgoing::Client.new(:version => @handshake.version, :data => message, :type => type)
  @connection.write frame.to_s
  @connection.flush
end