Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python套接字将大于127的整数值作为单个字节发送_Python_Sockets - Fatal编程技术网

Python套接字将大于127的整数值作为单个字节发送

Python套接字将大于127的整数值作为单个字节发送,python,sockets,Python,Sockets,我使用的是Python3,我希望发送一个大于127的整数作为单字节。正如预期的那样,我无法使用chr()函数实现这一点,因为该函数将其转换为2个字节。当我使用str()时,它会将其转换为我不想要的3个独立字节。 我试过了,但似乎找不到任何解决办法 一般来说,您应该尝试在bytestring(bytes)上执行面向字节的操作,在字符串(str)上执行面向文本的(或至少是面向USV的)操作。因此,不要试图将消息构造为单个最终编码的字符串: message_identifier = chr(50)

我使用的是Python3,我希望发送一个大于127的整数作为单字节。正如预期的那样,我无法使用chr()函数实现这一点,因为该函数将其转换为2个字节。当我使用str()时,它会将其转换为我不想要的3个独立字节。
我试过了,但似乎找不到任何解决办法

一般来说,您应该尝试在bytestring(
bytes
)上执行面向字节的操作,在字符串(
str
)上执行面向文本的(或至少是面向USV的)操作。因此,不要试图将消息构造为单个最终编码的字符串:

message_identifier =  chr(50)
message_name = 'Hello '
message_data_size = '160'.encode().decode() # clueless here

frame = (message_identifier + message_name + (message_data_size)) # don't know what to do with message_data_size

byt = frame.encode()
当逻辑将边界从文本传递到字节时进行编码:

message_identifier = bytes([50])  # or b'\x32', or b'2'
message_name = 'Hello '
message_data_size = bytes([160])

frame = message_identifier + message_name.encode('utf-8') + message_data_size

您使用什么函数发送字符串?我想它需要字节。(
字节([128])
)还有一些消息文本。所以最终我必须把它附加到一个字符串中。我不知道如何将例如160作为单个字节追加。您也可以先使用
str.encode
将字符串转换为字节。您使用什么函数发送字符串?我使用的是python套接字库中的socket.send()函数。此函数接受字符串
套接字。在Python 3中,send
不接受字符串。它需要字节。你能展示你的代码吗?这很有效。谢谢你这么完美的解释,伙计!:)