Instantly share code, notes, and snippets.

Embed
What would you like to do?
To establish a TCP-connection and be keeping it alive
#!/bin/bash
function log {
echo $(date) ' >> ' $* >&2
}
function die {
echo $* >&2
exit 1
}
while getopts ":m:h:p:" OPT; do
case "${OPT}" in
m)
MODE="${OPTARG}"
;;
h)
HOST="${OPTARG}"
;;
p)
PORT="${OPTARG}"
;;
\?)
die "Invalid option: -${OPTARG}"
;;
:)
die "Option -${OPTARG} requires an argument."
;;
esac
done
case "${MODE}" in
client)
[[ -z "${HOST}" ]] && die "Host isn't defined"
[[ -z "${PORT}" ]] && die "Port isn't defined"
socat TCP:${HOST}:${PORT} EXEC:"${0} -m client-ping",su-d=nobody
;;
client-ping)
PING=1
while :; do
# Sending ping
echo -e "$(date +%s)\t${PING}"
# Receiving pong
read STRING
# Checking latency
TIME_NEW="$(date +%s)"
if [[ ! -z "${TIME_OLD}" ]]; then
LATENCY=$(( ${TIME_NEW} - ${TIME_OLD} ))
if [[ "${LATENCY}" -gt 2 ]]; then
log "The latency is too high (${TIME_NEW} - ${TIME_OLD} = ${LATENCY})"
fi
fi
TIME_OLD="${TIME_NEW}"
# Checking sequence delta
PONG="$(echo "${STRING}" | cut -f 2)"
[[ -z ${PONG} ]] && die "Invalid reply: ${STRING}"
STEP=$(( ${PONG} - ${PING} ))
[[ "${STEP}" -ne 1 ]] && log "Unexpected sequence step (${PING} - ${PONG} = ${STEP})"
PING=$(( ${PONG} + 1 ))
# Sleeping
sleep 1
done
;;
server)
[[ -z "${PORT}" ]] && die "Port isn't defined"
while : ; do
socat TCP-LISTEN:${PORT},fork,su=nobody EXEC:"${0} -m server-ping"
sleep 1
log "Restarting"
done
;;
server-ping)
log "${SOCAT_PEERADDR} connected"
while :; do
read STRING
PING="$(echo "${STRING}" | cut -f 2)"
[[ -z ${PING} ]] && die "Invalid request: ${STRING}"
PONG=$(( ${PING} + 1 ))
echo -e "$(date +%s)\t${PONG}"
#
[[ $(( ${PONG} % 10000 )) -eq 0 ]] && log "Sent the ${PONG}'th pong!"
done
;;
*)
die "Invalid mode: ${MODE}"
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment