Class: WsSyncClient
- Inherits:
-
Object
- Object
- WsSyncClient
- Defined in:
- lib/ws_sync_client.rb
Overview
Synchronous socket.
Class Method Summary collapse
-
.raw_socket(host, port, timeout = 30) ⇒ Socket
Create a raw Socket connected to a host and port.
Instance Method Summary collapse
-
#close(code = 0, reason = '') ⇒ Object
Closes the WebSocket.
-
#initialize(url, options = {}) ⇒ WsSyncClient
constructor
Create a socket.
-
#recv_frame ⇒ String
Receive a WebSocket frame.
-
#send_frame(data) ⇒ Object
Send a WebSocket frame.
Constructor Details
#initialize(url, options = {}) ⇒ WsSyncClient
Create a socket.
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/ws_sync_client.rb', line 12 def initialize(url, = {}) @url = url @handshake = WebSocket::Handshake::Client.new url: @url if [:raw] @socket = [:raw] else @socket = self.class.raw_socket @handshake.host, @handshake.port end @max_recv = 4096 handshake @closed = false @incoming = WebSocket::Frame::Incoming::Client.new( version: @handshake.version) if leftovers = @handshake.leftovers @incoming << leftovers end end |
Class Method Details
.raw_socket(host, port, timeout = 30) ⇒ Socket
Create a raw Socket connected to a host and port.
123 124 125 126 127 128 129 130 131 132 133 |
# File 'lib/ws_sync_client.rb', line 123 def self.raw_socket(host, port, timeout = 30) Addrinfo.foreach host, port, nil, :STREAM, nil, Socket::AI_NUMERICSERV do |info| begin return info.connect rescue StandardError # Try the next address. end end nil end |
Instance Method Details
#close(code = 0, reason = '') ⇒ Object
Closes the WebSocket.
72 73 74 75 76 77 78 79 |
# File 'lib/ws_sync_client.rb', line 72 def close(code = 0, reason = '') return if @closed frame = WebSocket::Frame::Outgoing::Client.new version: @handshake.version, data: '', type: :close @socket.send frame.to_s, 0 @socket.close @closed = true end |
#recv_frame ⇒ String
Receive a WebSocket frame.
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/ws_sync_client.rb', line 44 def recv_frame loop do frame = @incoming.next if frame.nil? recv_bytes next end case frame.type when :text return frame.data when :binary return frame.data when :ping send_pong frame.data when :pong # Ignore pong, since we don't ping. when :close @socket.close @closed = true end end end |
#send_frame(data) ⇒ Object
Send a WebSocket frame.
35 36 37 38 39 |
# File 'lib/ws_sync_client.rb', line 35 def send_frame(data) frame = WebSocket::Frame::Outgoing::Client.new version: @handshake.version, data: data, type: :text @socket.send frame.to_s, 0 end |