You need to expand you protocol. Here are some ideas based on existing protocols:

HTTP

The size of the body ("Content-Length") is transmitted before the body itself, so the receiver knows when to stop listening for the body and start listening for another request or response.

Pro: Trivial to implement.
Con: Sender needs to know data's length in advance.
Con: Fails poorly when an error occurs.

FTP

A command connecion is maintained. Commands are exchanged to create new connections over which data is transfered.

Pro: Handles errors easily.
Con: More complex to implement.
Con: Harder for firewalls and proxies to handle.

SLIP

Packets are terminated with a special character ("\0300") that is not allowed to exist anywhere else in the stream. An encoding mechanism is provided to transmit these special characters as data ("\0300" is encoded as "\0333\0334" and "\0333" is encoded as "\0333\0335").

Pro: Easy to implement.
Pro: Sender doesn't need to know data's length in advance.
Pro: Can handle errors without breaking the connection.

Update: Added pros and cons.


In reply to Re: How to end socket file transfer without closing socket by ikegami
in thread How to end socket file transfer without closing socket by redss

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.