93 lines
1.5 KiB
Crystal
93 lines
1.5 KiB
Crystal
|
require "http/web_socket"
|
||
|
require "option_parser"
|
||
|
|
||
|
require "./colors"
|
||
|
require "./utils"
|
||
|
|
||
|
require "./ws"
|
||
|
|
||
|
uri = "ws://localhost:1234/pong"
|
||
|
|
||
|
OptionParser.parse! do |parser|
|
||
|
parser.on "-u uri", "--uri uri", "URI" do |opturi|
|
||
|
uri = opturi
|
||
|
end
|
||
|
|
||
|
parser.on "-h", "--help", "Show this help" do
|
||
|
puts parser
|
||
|
exit 0
|
||
|
end
|
||
|
end
|
||
|
|
||
|
def read_then_print(ws : WebSocket)
|
||
|
m = read ws
|
||
|
puts "message: #{String.new(m)}"
|
||
|
end
|
||
|
|
||
|
def read_then_print_hexa(ws : WebSocket)
|
||
|
m = read ws
|
||
|
print_hexa(String.new(m), "#{CBLUE}Received message hexa#{CRESET}")
|
||
|
end
|
||
|
|
||
|
def read(ws : WebSocket)
|
||
|
m = ws.read
|
||
|
if m.nil?
|
||
|
raise "empty message"
|
||
|
end
|
||
|
|
||
|
m
|
||
|
end
|
||
|
|
||
|
def send_with_announce(ws : WebSocket, m : String)
|
||
|
puts "sending #{m}"
|
||
|
send ws, m
|
||
|
end
|
||
|
|
||
|
def send(ws : WebSocket, m : String)
|
||
|
ws.send m
|
||
|
end
|
||
|
|
||
|
def send(ws : WebSocket, m : Slice)
|
||
|
ws.send m
|
||
|
end
|
||
|
|
||
|
|
||
|
begin
|
||
|
ws = WebSocket.new(URI.parse(uri))
|
||
|
|
||
|
puts "connection done: sending pong"
|
||
|
|
||
|
ws.on_close do |socket|
|
||
|
puts "socket is closing"
|
||
|
exit 0
|
||
|
end
|
||
|
|
||
|
if uri.ends_with? ".JSON"
|
||
|
json_message = STDIN.gets_to_end
|
||
|
json_message = json_message.chomp
|
||
|
# puts "json_message: #{json_message}"
|
||
|
final_json_message = "{ \"mtype\": 2, \"payload\": #{json_message} }"
|
||
|
puts "sending 10 messages: #{final_json_message}"
|
||
|
10.times do |i|
|
||
|
send ws, final_json_message
|
||
|
puts "sent message #{i}"
|
||
|
# send ws, "{ \"mtype\": 2, \"payload\": \"coucou\" }"
|
||
|
end
|
||
|
|
||
|
10.times do |i|
|
||
|
read ws
|
||
|
puts "read message #{i}"
|
||
|
end
|
||
|
else
|
||
|
send ws, to_message(2, STDIN.gets_to_end)
|
||
|
read ws
|
||
|
end
|
||
|
|
||
|
|
||
|
ws.read
|
||
|
ws.close
|
||
|
rescue e
|
||
|
puts "Exception: #{e}"
|
||
|
end
|
||
|
|