title: What is the correct procedure for multiple, sequential communications over a socket?
body: <p>I've been struggling along with sockets, making OK progress, but I keep running into problems, and feeling like I must be doing something wrong for things to be this hard.</p>
  
  <p>There are plenty of tutorials out there that implement a TCP client and server, usually where:</p>
  
  <ul>
  <li>The server runs in an infinite loop, listening for and echoing back data to clients.</li>
  <li>The client connects to the server, sends a message, receives the same thing back, <strong>and then quits</strong>.</li>
  </ul>
  
  <p>That I can handle. However, no one seems to go into the details of what you should and shouldn't be doing with sequential communication between the same two machines/processes. </p>
  
  <p>I'm after the general sequence of function calls for doing multiple messages, but for the sake of asking a real question, here are some constraints:</p>
  
  <ul>
  <li>Each event will be a single message client->server, and a single string response.</li>
  <li>The messages are pretty short, say 100 characters max.</li>
  <li>The events occur relatively slowly, max of say, 1 every 5 seconds, but usually less than half that speed.</li>
  </ul>
  
  <p>and some specific questions:</p>
  
  <ol>
  <li>Should the server be closing the connection after its response, or trying to hang on to the connection until the next communication?</li>
  <li>Likewise, should the client close the connection after it receives the response, or try to reuse the connection?</li>
  <li>Does a closed connection (either through <code>close()</code> or through some error) mean the end of the communication, or the end of the life of the entire object?
  <ol>
  <li>Can I reuse the object by connecting again?</li>
  <li>Can I do so on the same port of the server?</li>
  <li>Or do I have reinstantiate another socket object with a fresh call to <code>socket.socket()</code>?</li>
  </ol></li>
  <li>What should I be doing to avoid getting 'address in use' errors?</li>
  <li>If a <code>recv()</code> times out, is the socket reusable, or should I throw it away? Again, can I start a new connection with the same socket object, or do I need a whole new socket?</li>
  </ol>