Client doesn't close connection to server after receiving all responses

天大地大妈咪最大 提交于 2021-01-28 06:16:30

问题


For a school project, I have to create a bash script which communicates with a distant netcat server and sends commands to this server, and gets back responses.

In my client script, I have a sendMessage function that sends messages to the server, and then displays the response from the server. My issue is that after receiving a response, netcat is still waiting for data from server and won't close the connection.

I already tried the -q argument, and I don't get my responses with it, the -w argument is almost what I want, but the minimum value is 1 second, which is not possible to use in my case.

Here is my function:

function sendMessage {
    netcat -w 1 "$ipAddress" "$port" <<< "$*"
}

I'm still searching on my side but I have to admit a little help would be very welcome.


回答1:


Finally found a working way (maybe not the best but at least it's perfectly doing what I want :D)

after all functions I send a "ENDRESPONSE" message, and on my client, I test if I have this message or not :

function sendMessage {
    while read line; do
        if [[ $line == "ENDRESPONSE" ]]; then
            break
        else
            echo $line
        fi
    done < <(netcat "$ipAddress" "$port" <<< "$*")
}

Anyway thanks for your help, I'll try to implement other solutions later !




回答2:


You can exec nc as coproc, send the line to the server, then use read with a timeout to read the response, check whether the response is complete and then close the connection by sending a signal to nc.

Instead of using nc you can perhaps also use bash TCP capabilities, like

exec 5<>/dev/tcp/"$HOST"/"$PORT"
read -t "$TIMEOUT" -n "$MAXLEN" line
exec 5<&- 5>&-


来源:https://stackoverflow.com/questions/50524320/client-doesnt-close-connection-to-server-after-receiving-all-responses

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!