websocketd/src/websocketc.cr

84 lines
1.5 KiB
Crystal
Raw Normal View History

2020-07-04 22:31:17 +02:00
require "http/web_socket"
require "option_parser"
2020-07-22 10:14:27 +02:00
require "ipc"
2020-07-04 22:31:17 +02:00
require "./colors"
require "./utils"
2020-07-22 10:14:27 +02:00
require "./lib_modifications.cr"
2020-07-04 22:31:17 +02:00
2020-07-22 10:14:27 +02:00
class CLI
class_property uri = "ws://localhost:1234/pong"
class_property rounds = 1
end
2020-07-04 22:31:17 +02:00
OptionParser.parse do |parser|
parser.on "-u uri", "--uri uri", "URI" do |opturi|
2020-07-22 10:14:27 +02:00
CLI.uri = opturi
end
parser.on "-r rounds", "--rounds nb-messages", "Nb messages to send." do |opt|
CLI.rounds = opt.to_i
2020-07-04 22:31:17 +02:00
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)
2020-07-22 10:14:27 +02:00
puts "reading a message"
m = ws.run_once
2020-07-04 22:31:17 +02:00
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 | Slice)
ws.send m
end
begin
2020-07-22 10:14:27 +02:00
ws = WebSocket.new(URI.parse(CLI.uri))
2020-07-04 22:31:17 +02:00
puts "connection done: sending pong"
ws.on_close do |socket|
puts "socket is closing"
exit 0
end
2020-07-22 10:14:27 +02:00
message = if CLI.uri.ends_with? ".JSON"
IPC::Message.new(0, 2.to_u8, 3.to_u8, STDIN.gets_to_end).to_json
2020-07-04 22:31:17 +02:00
else
2020-07-22 10:14:27 +02:00
IPC::Message.new(0, 2.to_u8, 3.to_u8, STDIN.gets_to_end).to_packet
end
puts "final message: #{message}"
CLI.rounds.times do |i|
send ws, message
pp! read ws
2020-07-04 22:31:17 +02:00
end
ws.close
2020-07-22 10:14:27 +02:00
# pp! ws.run_once
2020-07-04 22:31:17 +02:00
rescue e
puts "Exception: #{e}"
end