简体   繁体   English

套接字编程 - 以字节为单位发送

[英]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.

相关问题 如何使用套接字编程发送UDP数据/数据包而不使用python将其转换为字节? - how to send UDP data/packet using Socket programming without converting it into bytes using python? 我可以通过 Python 中的套接字编程访问 IP 摄像机 PTZ 端口并向其发送十六进制字节吗? - Can I access an IP Camera PTZ port through socket programming in Python and send hex bytes to it? Python:套接字编程的.send函数 - Python: .send function of socket programming 如何使用 Locust 发送套接字的字节 - How to use Locust to send bytes of a socket 使用套接字编程Python发送图像 - Send image using socket programming Python python 套接字编程类型错误:不需要像 object 这样的字节 str - python socket programming TypeError: bytes like object is required not str Python 字节似乎与套接字编程中应有的不同 - Python bytes seem different than it should be in socket programming 套接字编程:类型错误:需要类似字节的 object,而不是“str” - Socket programming: TypeError: a bytes-like object is required, not 'str' 如何通过 Python Socket 发送原始 XML 而不是字节数据? - How to send raw XML instead of bytes data over Python Socket? 是否可以强制 TCP 套接字在数据包丢失的情况下发送 0 字节 - python - Is it is possible to force TCP socket to send 0 bytes in case of packet losses - python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM