Search code examples
bashshelltcpnetcat

How to continuously send data to client from server


I want to continuously send data from server to client. On the client side, I only want the received data to be displayed. How to continuously send data to client? echo "Hello, client!" | nc did not work.

Thanks in advance

You can see example script of server side below:

#!/bin/bash

while true
do
    echo "Sending message to client..."
    echo "Hello, client!" | nc <ip> <port>
done

Solution

  • Your nc command is missing -l (listen) parameter to behave as a server.

    Try this:

    #!/bin/bash
    
    while true
    do  
        echo "Sending message to client..."
        echo "Hello, client!" | nc -l 10000
    done
    

    In another terminal, connect as a client as many times as you want and you'll see the message sent:

    $ nc localhost 10000
    Hello, client!
    ^C  
    $ nc localhost 10000
    Hello, client!
    ^C  
    

    EDIT: To send messages to the client without needing to reconnect, you can create a fifo, make the server read this fifo continuously and forward this data to the client:

    $ mkfifo fifo_toclient
    $ tail -f fifo_toclient | nc -l 10000
    

    Run the client side command as before:

    $ nc localhost 10000
    

    In another terminal and in the same directory, modify your script to write data to the pipe instead of directly to nc and run it:

    $ cat send_to_client.sh
    #!/bin/bash
    
    while true
    do  
        echo "Sending message to client..."
        echo "Hello, client!" > fifo_toclient
        sleep 1
    done
    $ bash ./send_to_client.sh
    

    And you should see the messages in the output of the client side.