[英]Socket programming -send in bytes
i saw that if i want to send in bytes something, i have to write s.send(b'your text')
.我看到如果我想用字节发送一些东西,我必须写s.send(b'your text')
。 That is good so far.到目前为止还不错。 But what happens if 'your text'
is stored in a variable (like a = 'your text'
) and i want to send the variable a
in bytes?但是,如果'your text'
存储在变量中(如a = 'your text'
)并且我想以字节为单位发送变量a
会发生什么? I assumes and tested:我假设并测试:
s.send(b 'a') #does not work,it will send only 'a' as byte
s.send(b(a)) #does not work, error 'b is not defined'
If you are using python3, you probably want the bytes function (which will in turn direct you to the docs of thebytesarray function for the detail).如果您使用的是 python3,您可能需要字节 function (这将引导您查看字节数组function的文档以获取详细信息)。
You need to know the encoding of your your text
in order to convert it to bytes.您需要知道your text
的编码才能将其转换为字节。 From the docs:从文档:
If [the source] is a string, you must also give the encoding (and optionally, errors) parameters;如果 [the source] 是一个字符串,您还必须提供编码(以及可选的错误)参数; bytearray() then converts the string to bytes using str.encode(). bytearray() 然后使用 str.encode() 将字符串转换为字节。
So you will want something like s.send(bytes(a, 'utf-8'))
.所以你会想要像s.send(bytes(a, 'utf-8'))
这样的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.