简体   繁体   English

将tcp客户端套接字类从python2转换为python3

[英]converting a tcp client socket class from python2 to python3

I need to write a tcp client that runs in the background. 我需要编写一个在后台运行的tcp客户端。 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 . 我想在我的项目中实现它,因为我发现它比标准库中的示例或PyMOTW-3中的模块更好 Problem is, it is written in Python2 and I keep getting an error with this method: 问题是,它是用Python2编写的,并且我用这种方法不断出错:

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. 在研究过程中,我意识到Py2和Py3在字符串解释方面有不同的行为。 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)! 因此,我基本上已经尝试过将“数据”或“块”进行解码/编码('UTF-8')的任何组合,但总而言之,我总是以这种方式结束chunk = self.socket.recv(n - len(data)) ,在那里我得到一个通用的“ MemoryError”(没有进一步的描述)!

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? 或者,有人可以建议我使用一个现成的类来为tcp客户端连接设置单独的线程吗?

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() 所以你应该使用一些可以影响chunk = self.socket.recv(n - len(data)).decode()

on the sending side you should encode as such: socket.send(data.encode()) 在发送方,您应该这样编码: socket.send(data.encode())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM