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>You shall never close a socket immediately after writing into a socket: the close could swallow still unsent data.</p>

<p>The correct workflow is what is called a <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms738547%28v=vs.85%29.aspx" rel="nofollow">graceful shutdown</a>:</p>

<ul>
<li>the part that wants to close the connection uses a shutdown-write on the socket and keeps on reading</li>
<li>the other part detects a 0 bytes read from the socket which is sees as an end of file. It closes its socket</li>
<li>the initiator detects a 0 bytes read and can safely close the socket</li>
</ul>

<p>So the <code>finally</code> part becomes:</p>

<pre><code>finally:
  try:
    sock.shutdown(socket.SHUT_WR)
    while True:
        dummy = sock.recv(1024)
        if len(dummy) == 0: break
  finally:
    sock.close()
</code></pre>

python socketserver socat