Looking to emulate the functionality of socat in Python
<p>I need to send a string to a particular port on localhost using python.</p>

<p>I can achieve this by using socat on the command line like such:</p>

<pre><code>cat &lt;text file containing string to send&gt; | socat stdin tcp-connect:127.0.0.1:55559
</code></pre>

<p>I don't want to run the socat command as a subcommand so I'd like to know how to get this working using a python module.</p>

<p>My attempts at using sockets failed. Below is a script I was using which wasn't achieving the desired effect.</p>

<pre><code>    import socket
    HOST, PORT = "127.0.0.1", 55559
    jsonString = '{"name":"VideoStreamStatus","parameters":{"name":"video_0_0"}}'

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        # Connect to server and send data
        print "Attempting connection"
        sock.connect((HOST, PORT))
        print "Sending json string"
        sock.sendall(jsonString)
        print "String sent"

    finally:
        sock.close()

    print "Sent:     {}".format(jsonString)
</code></pre>

<p>The python script was executing without any errors but there wasn't any effect on the process which was receiving the socat data. Python script output below:</p>

<pre><code>    Attempting connection
    Sending json string
    Sent:     {"name":"VideoStreamStatus","parameters":{"name":"video_0_0"}}
</code></pre>

<p>Is there something I'm doing wrong in the socket script or is there a different method I can use in Python? I'd appreciate any advice. Thanks.</p>

<p>Edit: The server I'm trying to send strings to is part of a C++ program using boost asio acceptor to listen for tcp connections on a specific address and port.</p>

<p>According to <a href="https://linux.die.net/man/1/socat" rel="nofollow">the socat man page</a>,</p>

<blockquote>
  <p>When one channel has reached EOF, the write part of the other channel is shut down. Then, socat waits <code>timeout</code> seconds before terminating. Default is 0.5 seconds. </p>
</blockquote>

<p>Perhaps you need to defer your close by 0.5 seconds, like so:</p>

<pre><code>finally:
    #sock.close()
    sock.shutdown(socket.SHUT_WR)
    time.sleep(0.5)
    sock.close()
</code></pre>

<p>Or, perhaps you need to absorb the server's shutdown message, like so:</p>

<pre><code>finally:
    #sock.close()
    sock.shutdown(socket.SHUT_WR)
    sock.recv(999999)
    sock.close()
</code></pre>

python socketserver socat