Class: Wands::WebSocket
- Inherits:
-
Object
- Object
- Wands::WebSocket
- Extended by:
- Forwardable
- Includes:
- Protocol::WebSocket::Headers, JavaScript::WebSocket
- Defined in:
- lib/wands/web_socket.rb
Overview
This is a class that represents WebSocket, which has the same interface as TCPSocket.
The WebSocket class is responsible for reading and writing messages to the server.
Example usage:
web_socket = WebSocket.open(‘localhost’, 2345) web_socket.write(“Hello World!”)
puts web_socket.gets
web_socket.close
Class Method Summary collapse
Instance Method Summary collapse
- #close ⇒ Object
- #gets ⇒ Object
-
#initialize(socket) ⇒ WebSocket
constructor
A new instance of WebSocket.
- #puts(message) ⇒ Object
- #read(length) ⇒ Object
- #write(message) ⇒ Object
Methods included from JavaScript::WebSocket
Constructor Details
#initialize(socket) ⇒ WebSocket
Returns a new instance of WebSocket.
48 49 50 51 |
# File 'lib/wands/web_socket.rb', line 48 def initialize(socket) @socket = socket @binary_message = "".b end |
Class Method Details
.open(host, port) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/wands/web_socket.rb', line 33 def self.open(host, port) socket = TCPSocket.new(host, port) request = UpgradeRequest.new(host, port) socket.write(request.to_s) socket.flush response = HTTPResponse.new response.parse(socket) raise ResponseException.new("Bad Status", response) unless response.status == "101" request.verify response new(socket) end |
Instance Method Details
#close ⇒ Object
87 88 89 90 |
# File 'lib/wands/web_socket.rb', line 87 def close @socket.close @socket = nil end |
#gets ⇒ Object
53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/wands/web_socket.rb', line 53 def gets framer = Protocol::WebSocket::Framer.new(@socket) frame = framer.read_frame case frame when Protocol::WebSocket::TextFrame frame.unpack when Protocol::WebSocket::CloseFrame nil else raise "frame is not a text" end end |
#puts(message) ⇒ Object
67 68 69 70 |
# File 'lib/wands/web_socket.rb', line 67 def puts() frame = Protocol::WebSocket::TextFrame.new(true, ) frame.write(@socket) end |
#read(length) ⇒ Object
72 73 74 75 76 77 78 79 80 |
# File 'lib/wands/web_socket.rb', line 72 def read(length) @binary_message = read_next_binary_frame if @binary_message.size.zero? raise "not enough data." if @binary_message.size < length data = @binary_message.byteslice(0, length) @binary_message = @binary_message.byteslice(length, @binary_message.size - length) data end |
#write(message) ⇒ Object
82 83 84 85 |
# File 'lib/wands/web_socket.rb', line 82 def write() frame = Protocol::WebSocket::BinaryFrame.new(true, ) frame.write(@socket) end |