I need to write a tcp client that runs in the background. I found an interesting class that does exactly what I need at this link: Code sample - socket client thread . I'd like to implement it in my project because I find it to be better than the examples in the standard library or the modules in PyMOTW-3 . Problem is, it is written in Python2 and I keep getting an error with this method:
def _recv_n_bytes(self, n):
data = ''
while len(data) < n:
chunk = self.socket.recv(n - len(data))
print(chunk)
if chunk == '':
break
data += chunk
return data
During my research I've come to realize that Py2 and Py3 have a different behavior as to string interpretation. So I've tried basically any combination of decoding/encoding('UTF-8') the 'data' or the 'chunk', but somehow I end always end up at this line chunk = self.socket.recv(n - len(data))
, where I get a generic 'MemoryError' (no further description)!
Does anyone know what's going on? Or alternatively, can anyone suggest me a ready-made class to set up a separate thread for a tcp client connection?
Thanks.
Recently playing with sockets myself an I ran into the same problem. What you should do is encode any data you are sending to the receiver and decode any data that you are receiving at the client.
so you should use something to the affect of chunk = self.socket.recv(n - len(data)).decode()
on the sending side you should encode as such: socket.send(data.encode())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.