title: python socket file transfer
body: <p>I'm trying to write transfer files or chunks of data over a socket. I feel as if I'm reinventing the wheel, but my searches for a simple solution have failed (everything I find is either too simple or too complex).  The server would run on a phone running python 2.5.4. The intended application would be to sync music files between the phone and a host computer. </p>
  
  <p>This is the guts of what I have, which appears to work. I send and receive 'ok' to break up streams. </p>
  
  <p>Is sending 'ok' back and forth essentially as stop bits to break up streams of data a reasonable technique?</p>
  
  <p>Is there a standard way to do this?</p>
  
  <p>Running any sort of library server (ftp, http) on the phone is not a useful solution given the limits of the phone's memory and processing power.</p>
  
  <p>server:</p>
  
  <pre><code>import socket
  
  c = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  c.bind(('', 1234))
  c.listen(1)
  s,a = c.accept()
  
  while True:
      data = s.recv(1024)
      cmd = data[:data.find('\n')]
  
      if cmd == 'get':
          x, file_name, x = data.split('\n', 2)
          s.sendall('ok')
          with open(file_name, 'rb') as f:
              data = f.read()
          s.sendall('%16d' % len(data))
          s.sendall(data)
          s.recv(2)
  
      if cmd == 'end':
          s.close()
          c.close()
          break
  </code></pre>
  
  <p>client:</p>
  
  <pre><code>import socket
  
  s = socket.socket()
  s.connect(('192.168.1.2', 1234))
  
  def get_file(s, file_name):
      cmd = 'get\n%s\n' % (file_name)
      s.sendall(cmd)
      r = s.recv(2)
      size = int(s.recv(16))
      recvd = ''
      while size &gt; len(recvd):
          data = s.recv(1024)
          if not data: 
              break
          recvd += data
      s.sendall('ok')
      return recvd
  
  print get_file(s, 'file1')
  print get_file(s, 'file2')
  s.sendall('end\n')
  </code></pre>