ipcd/tests/test-ws.cr

75 lines
1.1 KiB
Crystal
Raw Normal View History

2020-01-16 17:43:02 +01:00
require "http/web_socket"
require "../src/colors"
require "../src/utils"
2020-02-04 02:06:13 +01:00
require "ipc"
require "../src/lib_modifications.cr"
2020-01-16 17:43:02 +01:00
require "json"
2020-02-04 02:06:13 +01:00
class TestIPC
property ipcc : IPC::Client
2020-02-04 02:06:13 +01:00
property is_json : Bool
def initialize(service_name : String)
@is_json = uri.ends_with? ".JSON"
@ipcc = IPC::Client.new service_name
2020-02-04 02:06:13 +01:00
end
# TODO
#def run
# yield @ipcc
# ipcc.close
#end
end
2020-01-16 17:43:02 +01:00
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
2020-02-04 02:06:13 +01:00
m = nil
loop do
m = @ws.run_once
2020-01-16 17:43:02 +01:00
if m.nil?
raise "empty message"
end
2020-02-04 02:06:13 +01:00
# remove ping messages, they are not application-relevent
unless m.is_a?(HTTP::WebSocket::Ping)
break
end
puts "received a ping message, skipping"
2020-01-16 17:43:02 +01:00
end
m
end
2020-02-04 02:06:13 +01:00
def send(type : Int32, data : String)
m : String | Bytes
2020-01-16 17:43:02 +01:00
if @is_json
m = IPC::Message.new(0, 1.to_u8, type.to_u8, data).to_json
2020-02-04 02:06:13 +01:00
else
m = IPC::Message.new(0, 1.to_u8, type.to_u8, data).to_packet
2020-01-16 17:43:02 +01:00
end
@ws.send m
end
def close
@ws.close
end
end