更新时间:2023-09-08 21:26:40
这个错误的原因是在Python 3中,字符串是Unicode,但是在网络上传输时,数据需要是字节.所以...一些建议:
The reason for this error is that in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes instead. So... a couple of suggestions:
c.sendall()
而不是 c.send()
以防止可能出现的问题,即您可能没有通过一次调用发送整个 msg(请参阅 docs).'b'
:c.sendall(b'Thank you for connection')
c.sendall()
instead of c.send()
to prevent possible issues where you may not have sent the entire msg with one call (see docs).'b'
for bytes string: c.sendall(b'Thank you for connecting')
***解决方案(应同时使用 2.x 和 3.x):
Best solution (should work w/both 2.x & 3.x):
output = 'Thank you for connecting'
c.sendall(output.encode('utf-8'))
结语/背景:这在 Python 2 中不是问题,因为字符串已经是字节字符串——您的 OP 代码可以在该环境中完美运行.Unicode 字符串在 1.6 & 版本中被添加到 Python 中.2.0 但在 3.0 成为默认字符串类型之前退居二线.另请参阅 this similar question 以及 this one.
Epilogue/background: this isn't an issue in Python 2 because strings are bytes strings already -- your OP code would work perfectly in that environment. Unicode strings were added to Python in releases 1.6 & 2.0 but took a back seat until 3.0 when they became the default string type. Also see this similar question as well as this one.