Python套接字错误TypeError:需要类似字节的对象,而不是带有send函数的'str'

sqlsqlsql:

我正在尝试创建一个程序,该程序将打开本地计算机上的端口,并让其他人通过netcat连接到该端口。我当前的代码是。

s = socket.socket()
host = '127.0.0.1'
port = 12345
s.bind((host, port))

s.listen(5)
while True:
    c, addr = s.accept()
    print('Got connection from', addr)
    c.send('Thank you for connecting')
    c.close()

我是Python和套接字的新手。但是,当我运行以下代码时,它将允许我使用以下命令发送netcat连接:

nc 127.0.0.1 12345

但是然后在我的Python脚本上,我得到了c.send的错误:

TypeError: a bytes-like object is required, not 'str'

我基本上只是想打开一个端口,允许netcat连接并在该计算机上安装一个完整的外壳。

wescpy:

发生此错误的原因是,在Python 3中,字符串是Unicode,但是在网络上传输时,数据需要改为字节。所以...一些建议:

  1. 建议使用c.sendall()而不是以c.send()避免可能的问题,在这种情况下您可能没有通过一个呼叫就发送了整个msg(请参阅docs)。
  2. 对于文字,添加'b'for字节字符串:c.sendall(b'Thank you for connecting')
  3. 对于变量,您需要将Unicode字符串编码为字节字符串(请参见下文)

最佳解决方案(应同时使用2.x和3.x):

output = 'Thank you for connecting'
c.sendall(output.encode('utf-8'))

结束语/背景知识:这在Python 2中不是问题,因为字符串已经是字节字符串了-您的OP代码将在该环境中完美运行。Unicode字符串已在1.6和2.0版本中添加到Python中,但在它们成为默认字符串类型之前一直落后到3.0。也看到这个类似的问题,以及这一个

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Python gnupg“类型错误:需要类似字节的对象,而不是'str'”

使用Python 3.5,抛出错误:TypeError:需要一个类似字节的对象,而不是'str'

TypeError:需要类似字节的对象,而不是 Python 2.7 中的“str”错误

Python错误:TypeError:需要一个类似字节的对象,而不是'str'

套接字编程 - 需要一个类似字节的对象,而不是“str”

如何删除“TypeError:需要类似字节的对象,而不是“str””

错误:需要一个类似字节的对象,而不是'str'

TypeError:需要一个类似字节的对象,而不是由拆分函数引起的'str'

如何解决Json错误:TypeError:需要一个类似字节的对象,而不是'str'

如何解决错误:TypeError:需要类似字节的对象,而不是FLASK-MAIL的“ str”?

URL打开,解码编码错误TypeError:需要类似字节的对象,而不是'str'

TypeError:预期的类似字节的对象,而不是str

Python 3.6:TypeError:在尝试打印页面中的所有链接时,需要一个类似字节的对象,而不是'str'

Python 3-TypeError:需要一个类似字节的对象,而不是'str'

Python 2到3“ TypeError:需要一个类似字节的对象,而不是'str'”

TypeError:需要一个类似字节的对象,而不是'str'–用Python保存JSON数据

Python 3.7 TypeError:需要一个类似字节的对象,而不是'str'

python 3.5:“ TypeError:memoryview:需要一个类似字节的对象,而不是'str'”

Python3 TypeError:需要一个类似字节的对象,而不是“str”

TypeError:需要一个类似字节的对象,而在python和CSV中不是'str'

TypeError:需要一个类似字节的对象,而在python和CSV中不是'str'

Python3 .replace产生TypeError:需要一个类似字节的对象,而不是'str'

Python 3,TypeError:需要一个类似字节的对象,而不是'str'

python3:类型错误:需要类似字节的对象,而不是“str”

需要一个类似字节的对象,而不是python中的“ str”错误

类型错误:需要一个类似字节的对象,不是“str”,但类型显示字节

使用python计算excel中的重复行,并且我收到错误TypeError:需要一个类似字节的对象,而不是'str'

TypeError:需要一个类似字节的对象,而在Python 3中打开Python 2 Pickle文件时不是'str'

TypeError:在Python3中写入文件时需要一个类似字节的对象,而不是'str'