diff --git a/lib/socket.io-client-simple.rb b/lib/socket.io-client-simple.rb index 1cfa2f8..a83ae31 100644 --- a/lib/socket.io-client-simple.rb +++ b/lib/socket.io-client-simple.rb @@ -7,6 +7,7 @@ require 'socket.io-client-simple/version' require 'socket.io-client-simple/error' require 'socket.io-client-simple/client' +require 'socket.io-client-simple/byte_buffer' module SocketIO module Client diff --git a/lib/socket.io-client-simple/byte_buffer.rb b/lib/socket.io-client-simple/byte_buffer.rb new file mode 100644 index 0000000..3055bca --- /dev/null +++ b/lib/socket.io-client-simple/byte_buffer.rb @@ -0,0 +1,19 @@ +module SocketIO + module Client + module Simple + + def self.as_byte_buffer(data) + ByteBuffer.new(data) + end + + class ByteBuffer + attr_accessor :buffer + + def initialize(byte_array) + return unless byte_array.is_a?(Array) + @buffer = byte_array.unshift(4).pack('C*') + end + end + end + end +end diff --git a/lib/socket.io-client-simple/client.rb b/lib/socket.io-client-simple/client.rb index d4a48ad..41fd687 100644 --- a/lib/socket.io-client-simple/client.rb +++ b/lib/socket.io-client-simple/client.rb @@ -19,6 +19,7 @@ def initialize(url, opts={}) @url = url @opts = opts @opts[:transport] = :websocket + @path = @opts.delete(:path) || "/socket.io" @reconnecting = false @state = :disconnect @auto_reconnection = true @@ -49,7 +50,7 @@ def initialize(url, opts={}) def connect query = @opts.map{|k,v| URI.encode "#{k}=#{v}" }.join '&' begin - @websocket = WebSocket::Client::Simple.connect "#{@url}/socket.io/?#{query}" + @websocket = WebSocket::Client::Simple.connect "#{@url}#{@path}/?#{query}" rescue Errno::ECONNREFUSED => e @state = :disconnect @reconnecting = false @@ -116,8 +117,9 @@ def open? def emit(event_name, *data) return unless open? return unless @state == :connect - data.unshift event_name - @websocket.send "42#{data.to_json}" + data.each do |packet| + is_binary?(packet) ? send_binary(event_name, packet) : send_data(event_name, packet) + end end def disconnect @@ -126,8 +128,30 @@ def disconnect @state = :disconnect end - end + private + + def is_binary?(packet) + packet.is_a?(SocketIO::Client::Simple::ByteBuffer) + end + + def send_data(event_name, *data) + data.unshift event_name + @websocket.send "42#{data.to_json}" + end + def send_binary(event_name, packet) + header = binary_header.unshift event_name + @websocket.send "451-#{header.to_json}" + @websocket.send packet.buffer, type: :binary + end + + def binary_header + [{ + _placeholder: true, + num: 0 + }] + end + end end end end diff --git a/lib/socket.io-client-simple/version.rb b/lib/socket.io-client-simple/version.rb index d6f3f79..ac11b96 100644 --- a/lib/socket.io-client-simple/version.rb +++ b/lib/socket.io-client-simple/version.rb @@ -1,7 +1,7 @@ module SocketIO module Client module Simple - VERSION = "1.2.1" + VERSION = "1.2.2" end end end