how twisted server detects an incomplete message
<p>I am right now implementing a twisted client and twisted server. 
The question is how does the server detect if a message that is sent by client is completed?</p>

<p>For example, there are 2 clients sending messages to server, the message is a python list which has only several elements, respectively. The 2nd client sends the message very short time after the 1st client does. </p>

<p>Since it's async, the server will switch to serve the 2nd client, leaving the message of 1st client half-processed. So how do I do to let the server know this message is not complete? Thanks in advance. </p>

<p>You want to implement some sort of <em>protocol</em> (not to be confused with <code>twisted.internet.protocol</code>) which has some sort of delimiter signifying the beginning and end of a message and how long your message will be. For example, let's define a protocol which implements the following rules:</p>

<ol>
<li>All messages start with <code>{</code></li>
<li>An <code>int</code> number of bytes which will contain the message body, followed by <code>:</code></li>
<li>The message body</li>
<li>An end tag <code>}</code></li>
</ol>

<p>An example expected message would look like:</p>

<pre><code>{10:Hey Earth!}
</code></pre>

<p>Twisted provides many interfaces to do this for you, so you don't really have to do this on your own. There's <a href="http://twistedmatrix.com/documents/current/core/howto/servers.html#helper-protocols" rel="nofollow"><code>LineReceiver</code></a> which combines bytes until a line break. There's the <a href="http://twistedmatrix.com/documents/current/core/howto/amp.html" rel="nofollow">AMP protocol</a> and <a href="https://twistedmatrix.com/documents/current/api/twisted.protocols.basic.NetstringReceiver.html" rel="nofollow"><code>NetStrings</code></a>, which is similar to the example I provided previously.</p>

<h2>References:</h2>

<ul>
<li><a href="http://krondo.com/a-poetry-transformation-server/" rel="nofollow">http://krondo.com/a-poetry-transformation-server/</a> - search for <code>netstring</code> you should find a good example of how to write one for yourself.</li>
</ul>

python twisted