I can connect to WS with wscat, I can send commands from console, but I have no idea how to pass commands from script. I've tried few way, and always WAS is closed before commands are passed.
Generally I wnt something that will: 1. connect to WS 2. Send commands one by one, from list 3. Save input and output to file
wscat is a poorly-chosen tool for the job; it isn't written to follow conventions that make it suitable for scripted use (such as keeping prompts on stderr rather than stdout; or suppressing prompts when output is not to a TTY; or treating an EOF as a signal to close a connection). Consider websocat instead:
#!/usr/bin/env bash
runscript() {
commands=( "first command" "second command" "third command" )
for command in "${commands[@]}"; do
echo "Writing command to server" >&2
echo "$command"
echo "Reading response from server (assuming exactly one line)" >&2
read -r line
echo "Received response: $line" >&2
done
# kill websocat, even if the websocket doesn't get closed
kill "$PPID"
}
export -f runscript
websocat ws://echo.websocket.org sh-c:'exec bash -c runscript'
For simple things, you can use the -x parameter to give wscat some JSON to send after the connection is established, for example:
wscat --connect ws://example.com -w 1 -x '{"action": "helloWorld"}'
The -w 1 will wait for one second after sending the message in case any replies come back.
Of course doing this connects to the WebSocket, sends the message, waits the given time for replies, then disconnects, so it's not a great choice if you need to keep the connection open between messages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With