Discuss / Python / 我好奇你们的怎么没有这个错误

我好奇你们的怎么没有这个错误

Topic source

这是服务端的报错

Waiting for connection...
Accept new connection from 127.0.0.1:52348...
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Users\sw\AppData\Local\Programs\Python\Python38\lib\threading.py", li
ne 932, in _bootstrap_inner
    self.run()
  File "C:\Users\sw\AppData\Local\Programs\Python\Python38\lib\threading.py", li
ne 870, in run
    self._target(*self._args, **self._kwargs)
  File "E:\java\tcpServer.py", line 24, in tcplink
    sock.send('Hello, %s!' % data.decode('utf-8').encode('utf-8'))
TypeError: a bytes-like object is required, not 'str'

把服务端的

sock.send('Hello, %s!' % data.decode('utf-8').encode('utf-8'))

换成

sock.send(b'Hello, %s!' % data.decode('utf-8').encode('utf-8'))

就好了

漆园的鱼

#2 Created at ... [Delete] [Delete and Lock User]

你少打了个括号:

sock.send( ( 'Hello, %s!' % data.decode('utf-8') ).encode('utf-8') )
           ^这个

岁末凯歌

#3 Created at ... [Delete] [Delete and Lock User]

数据要从本地放到网络上传输,是不能用str形式的,必须要转换为字节码才能传,你的报错信息最下面一行就已经说明了这个问题,示例里经常出现decode('utf-8')就是字节码转字符串,详细可以回看字符串编码那一节


  • 1

Reply