TypeError:使用套接字时无法将“ bytes”对象转换为隐式str

ken596

因此,我正在尝试将代码从Python 2.7转换为Python 3,似乎有些变化。我正在尝试通过套接字接收二进制数据,但现在不起作用。这是我的代码。

编辑:我已经添加了我的发送代码。另外,我真的不喜欢它现在的工作方式,它过于复杂。如果可以的话,最好有一种更好的发送/接收数据的方法。

def recv(self):
    # Receive the length of the incoming message (unpack the binary data)
    dataLength = socket.ntohl(struct.unpack("I", self._recv(4))[0])

    # Receive the actual data
    return self._recv(dataLength)

def _recv(self, length):
    try:
        data = ''
        recvLen = 0
        while recvLen < length:
            newData = self.sock.recv(length-recvLen)

            if newData == '':
                self.isConnected = False
                raise exceptions.NetworkError(errors.CLOSE_CONNECTION, errno=errors.ERR_CLOSED_CONNECTION)

            data = data + newData # TypeError here
            recvLen += len(newData)

        return data
    except socket.error as se:
        raise exceptions.NetworkError(str(se))

def send(self, data):
    if type(data) is not str:
        raise TypeError()

    dataLength = len(data)

    # Send the length of the message (int converted to network byte order and packed as binary data)
    self._send(struct.pack("I", socket.htonl(dataLength)), 4)

    # Send the actual data
    self._send(data, dataLength)

def _send(self, data, length):
    sentLen = 0
    while sentLen < length:
        try:
            amountSent = self.sock.send(data[sentLen:])
        except Exception:
            self.isConnected = False
            raise exceptions.NetworkError(errors.UNEXPECTED_CLOSE_CONNECTION)

        if amountSent == 0:
            self.isConnected = False
            raise exceptions.NetworkError(errors.UNEXPECTED_CLOSE_CONNECTION)

        sentLen += amountSent
简单

Python 3以字节为单位发送数据,因此您必须解码为字符串

 data = data + newData.decode('utf-8')

 # or 

 data = data + newData.decode('ascii')

如果您需要字节数据,请使用

 data = b''

并保持无 .decode()

 data = data + newData

编辑:对于有问题的新代码。

发送时,您必须将字符串转换/编码为字节,然后再获取其长度。本机字符的Unicode长度为1,但可以使用2个字节(或更多)。

收到消息后,您必须处理字节b'',最后再将字节转换/解码为字符串。

查看# <--代码中的注释

def send(self, data):
    if not isinstance(data, str): # <-- prefered method
    #if type(data) is not str:
        raise TypeError()

    data = data.encode('utf-8') # <-- convert to bytes

    # get size of bytes
    dataLength = len(data)

    # Send the length of the message (int converted to network byte order and packed as binary data)
    self._send(struct.pack("I", socket.htonl(dataLength)), 4)

    # Send the actual data
    self._send(data, dataLength)


def recv(self):
    # Receive the length of the incoming message (unpack the binary data)
    dataLength = socket.ntohl(struct.unpack("I", self._recv(4))[0])

    # Receive the actual data
    return self._recv(dataLength).decode('utf-8') # <-- convert to string again

def _recv(self, length):
    try:
        data = b'' # <-- use bytes
        recvLen = 0
        while recvLen < length:
            newData = self.sock.recv(length-recvLen)

            #if newData == b'': # <-- use bytes
            if not newData:    # <-- or 
                self.isConnected = False
                raise exceptions.NetworkError(errors.CLOSE_CONNECTION, errno=errors.ERR_CLOSED_CONNECTION)

            data = data + newData # TypeError here
            recvLen += len(newData)

        return data
    except socket.error as se:
        raise exceptions.NetworkError(str(se))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TypeError:无法将“ int”对象隐式转换为str

TypeError:无法将“ int”对象隐式转换为str

TypeError:无法将“列表”对象隐式转换为str

TypeError:无法将“节点”对象隐式转换为str

TypeError:无法将“模块”对象隐式转换为str

无法将“字节”对象隐式转换为str

“无法将'float'对象转换为隐式str“

TypeError-无法将“用户”对象隐式转换为str

Tensorflow TypeError:无法将'numpy.int64'对象转换为隐式str

Python3错误:TypeError:无法将“字节”对象隐式转换为str

Python:TypeError:无法将“生成器”对象隐式转换为str

TypeError:无法将“ builtin_function_or_method”对象隐式转换为str

Masonite-TypeError:无法将“未定义”对象隐式转换为str

TypeError:无法将'int'对象转换为str隐式错误python

TypeError:无法将'int'对象隐式转换为str(python)

TypeError:对于Pascode系统,无法将“ int”对象隐式转换为str

Python 错误:写入 json 文件时无法将“列表”对象隐式转换为 str

TypeError:无法将int隐式转换为str

TypeError:无法将“ float”对象隐式转换为str或TypeError:-:“ str”和“ float”的不受支持的操作数类型

TypeError:无法在Fib中将'int'对象转换为隐式str

无法将'nonetype'对象隐式转换为str-Python3

python gettext错误:无法将'__proxy__'对象隐式转换为str

Boto3和Python3:无法将“字节”对象隐式转换为str

awscli 错误 - 无法将“NoneType”对象隐式转换为 str

python3无法将字节隐式转换为对象'str'

无法在python 3.4.3中将'int'对象隐式转换为str

“无法将'int'对象隐式转换为str”错误(Python)

无法将“ int”对象隐式转换为str。Python错误

无法将'int'对象隐式转换为str:Python 3+