Python 套接字发送缓冲区对比斯特
我正在尝试让一个基本服务器(从 Beginning Python 复制)来发送 str.
错误:
c.send( "XXX" )
TypeError: must be bytes or buffer, not str
它似乎在酸洗对象时起作用。我找到的所有示例似乎都能够毫无问题地发送字符串。
任何帮助将不胜感激,
斯蒂芬
import socket
import pickle
s = socket.socket()
host = socket.gethostname()
port = 80
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print( "Got Connection From ", addr )
data = pickle.dumps(c)
c.send( "XXX" )
#c.send(data)
c.close()
I am trying to get a basic server (copied from Beginning Python) to send a str.
The error:
c.send( "XXX" )
TypeError: must be bytes or buffer, not str
It seems to work when pickling an object. All of the examples I found, seem to be able to send a string no problem.
Any help would be appreciated,
Stephen
import socket
import pickle
s = socket.socket()
host = socket.gethostname()
port = 80
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print( "Got Connection From ", addr )
data = pickle.dumps(c)
c.send( "XXX" )
#c.send(data)
c.close()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来您尝试在 Python 3 中使用 Python 2.x 示例,并且发现了这些 Python 版本之间的主要区别之一。
对于Python< 3 “字符串”实际上是二进制字符串,“unicode 对象”是正确的文本对象(因为它们可以包含任何 Unicode 字符)。
在 Python 3 中,unicode 字符串是“常规字符串”(str),而字节字符串是单独的对象。
低级 I/O 只能使用数据(字节字符串)完成,而不能使用文本(字符序列)完成。对于 Python 2.x str 也是“二进制数据”类型。在 Python 3 中,这种情况不再存在,应该使用特殊的“数据”对象之一。对象被腌制为此类字节字符串。如果您想在代码中手动输入它们,请使用“b”前缀(b“XXX”而不是“XXX”)。
It seems you try to use Python 2.x examples in Python 3 and you hit one of the main differences between those Python version.
For Python < 3 'strings' are in fact binary strings and 'unicode objects' are the right text objects (as they can contain any Unicode characters).
In Python 3 unicode strings are the 'regular strings' (str) and byte strings are separate objects.
Low level I/O can be done only with data (byte strings), not text (sequence of characters). For Python 2.x str was also the 'binary data' type. In Python 3 it is not any more and one of the special 'data' objects should be used. Objects are pickled to such byte strings. If you want to enter them manually in code use the "b" prefix (b"XXX" instead of "XXX").
添加到 Jacek Konieczny 的答案:您还可以使用 str.encode()< /a> 从字符串中获取字节。如果变量中有字符串而不是文字,则可以调用encode,它将返回等效的字节序列。
To add to Jacek Konieczny's answer: You can also use str.encode() to get bytes from a string. If you have the string in a variable instead of a literal, you can call encode and it will return an equivalent series of bytes.