require "http/web_socket" require "../src/colors" require "../src/utils" require "../src/ws" require "json" class TestWS property ws : WebSocket property is_json : Bool def initialize(uri : String) @ws = WebSocket.new(URI.parse(uri)) @is_json = uri.ends_with? ".JSON" @ws.on_close do |socket| raise "socket is closing" end end def read m = @ws.read if m.nil? raise "empty message" end # remove ping messages, they are not application-relevent while m.is_a?(HTTP::WebSocket::Ping) puts "received a ping message, skipping" m = @ws.read if m.nil? raise "empty message" end end m end def send(type : Int32, data : String | Slice) m = to_message type, data # quick hack to send json messages if @is_json json_message = data.chomp final_json_message = "{ \"mtype\": #{type}, \"payload\": \"#{json_message}\" }" # puts "message: #{final_json_message}" m = final_json_message end @ws.send m end def close @ws.close end end