Note that there are some explanatory texts on larger screens.

plurals
  1. POPython socket recv (client-side)
    text
    copied!<p>i have to connect to an api via socket and send / recv some data. the company send me a php-example-file with this code for reading data from the socket:</p> <pre><code>function readAnswer() { $size = fgets($this-&gt;socketPtr, 64); $answer = ""; $readed = 0; while($readed &lt; $size) { $part = fread($this-&gt;socketPtr, $size - $readed); $readed += strlen($part); $answer .= $part; } return $answer; } </code></pre> <p>This works for me. But in python i get from times to times an error. not everything from the socket is recv. my python try looks like this:</p> <pre><code>def read_answer(self,the_socket,timeout=0.5): the_socket.setblocking(0) total_data=[] data='' begin=time.time() while 1: if total_data and time.time()-begin &gt; timeout: break elif time.time()-begin &gt; timeout*2: break try: data = the_socket.recv(8192) if data: total_data.append(data) begin=time.time() else: time.sleep(0.1) except: pass return ''.join(total_data) </code></pre> <p>i recv data as a dict / array. and from time to time i only get a int (msg length i think) so what would be a better way to read the data from socket. ah the api sends the data in a correct way, i checked this. it's only this little function ;(</p> <p>After using the code below (thanks falsetru) and added a readed=len(data) i run into another problem: this is the working php code:</p> <pre><code> function _parse_answer($answerData) { $result = array(); $lines = explode("\n", $answerData); $data = explode("&amp;", $lines[0]); foreach($data as $piece) { $keyval = explode("=", $piece, 2); $result[$keyval[0]] = $keyval[1]; } for($i=1;$i&lt;count($lines);$i++) { $result["csv"][]=$lines[$i]; } return $result; } </code></pre> <p>and this my crappy python code:</p> <pre><code>def parse_answer(self,data): #print "dd_demo_api: answer: (%s)" % (data) if data: result = {} lines = data.split("\n") index_list = 0 if len(lines) == 1: index_list = 0 else: index_list = 1 pieces = lines[index_list].split("&amp;") for x in pieces: keyval = x.split("=") result[keyval[0]] = keyval[1] iterlines = iter(lines) next(iterlines) next(iterlines) count = 1 result["csv"] = {} for x in iterlines: result["csv"][count] = x.split(";") return result else: return 0 </code></pre> <p>i think here is some optimization required? ;(</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload