我是shell編程的新手,我創建了一個腳本來打開與我的服務器的連接。我想讓這個腳本監聽客戶端節點的輸入並使用它來運行一個函數。用於調用sh腳本中的函數的netcat守護進程
這是我的過程。 運行腳本>打開監聽器>在第二臺計算機使用netcat來連接>名爲nodefunction
服務器我已經SERVER_PORT編碼爲「4444」
文件名上的腳本運行的函數:run_hangman
nc -l -k -v -p 4444 | bash hangman
文件名:劊子手
#!/bin/bash
msg_timeout=0
host_ows=1
server_port=4444
dubOws=xxx.xxx.xxx.xxx
initServer() {
hostIP=`ip -o addr show dev "eth0" | awk '$3 == "inet" {print $4}' | sed -r 's!/.*!!; s!.*\.!!'`
hostOws=`echo $hostIP | cut -d . -f 4`
}
servermsg(){ #message //if = --n, echos on same line
if [ "$1" != "--n" ]
then
echo `date +"%T"` "[SERVER] "$1
else
echo -n `date +"%T"` "[SERVER] "
fi
}
owsmsg(){ #message //if = --n, echos on same line
if [ "$1" != "--n" ]
then
echo `date +"%T"` "[OWS] "$1
else
echo -n `date +"%T"` "[OWS] "
fi
}
playermsg() {
if [ "$1" != "--n" ]
then
echo `date +"%T"` "[PLAYER] "$1
else
echo -n `date +"%T"` "[PLAYER] "
fi
}
question(){ #question, read, example
servermsg "$1"
if [ -n "$3" ]
then
servermsg "$3"
fi
read $2
echo ""
}
owsArray(){ #
for targetOws in $player_list
do
owsArray+=("OWS"$targetOws)
done
echo -n ${owsArray[*]}
echo
}
openSocket() {
servermsg "Starting the Game Listener"
servermsg "Opening Listener on port "$server_port
#nc -k -l $server_port |bash
#nc -kl -q 1 -p $server_port # This should create the listener & This is where everything stops.
servermsg "Now listening on port "$server_port
}
initServer
owsmsg "Starting server on OWS"$hostOws"..."
question "Enter all the OWSs that will play:" player_list "Example: 1 9 14 23"
echo $player_list
question "Type a category hint:" game_cat "Example: Type of Animal"
question "Type your word:" game_word "Example: zebra"
question "How many guesses:" game_guesses "Example: 7"
servermsg "OWS"$host_ows "has created a Hangman session"
servermsg "Players are:"; servermsg --n; owsArray
servermsg "Your word is "${#game_word}" letters long and players have "$game_guesses" guesses"
question "If this is all correct press enter, or CTRL+C to cancel"
openSocket
# I think I need a While script here to read the RAW input and run the playermsg function with the input?
我運行run_hangman文件,然後我通過我的節點計算機連接到它。我輸入以下行並回顯「1 2 3」,因爲這是我所需要的。我也不能在運行「run_hangman」的窗口中直接輸入「1 2 3」,就好像我按Enter鍵進入一個新行。
echo "1 2 3" >/dev/tcp/xxx.xxx.xxx.xxx/4444
服務器表明,它連接
Listening on [0.0.0.0] (family 0, port 4444)
14:52:24 [OWS] Starting server on OWS225...
14:52:24 [SERVER] Enter all the OWSs that will play:
14:52:24 [SERVER] Example: 1 9 14 23
Connection from [xxx.xxx.xxx.xxx] port 4444 [tcp/*] accepted (family 2, sport 41564)
Connection closed, listening again.
1 2 3
現在,一旦它到達openSocket就會讓我送多一個回聲,然後將其關閉的服務器上。我需要得到我認爲是一段時間的聲明,並讓它監聽像「playermsg」已經開始遊戲一樣的輸入,並讓它真正在服務器上運行該功能。
我將能夠得到這個運行,幾乎好像它必須在後臺?我一直在使用nc(1)作爲參考,有些網站說要嘗試-d
,那也不管用。