简体   繁体   English

您可以在python中压缩字节并将其发送吗?

[英]Can you compress bytes in python and send them?

I am writing a TCP python script, and I need the first 4 bytes to be the size of the file. 我正在编写一个TCP python脚本,我需要前4个字节作为文件的大小。

I got the size of the file by doing 我通过做得到文件的大小

SIZE_OF_FILE = os.path.getsize(infile.name)

The size is 392399 bytes. 大小为392399字节。

When I do 当我做

s.send(str(SIZE_OF_FILE).encode("utf-8"))

it sends the file, and then on my server I have 它发送文件,然后在我的服务器上

fileSize = conn.recv(4).decode('utf-8')

This should read the first 4 bytes, and extract the file size information, but it returns 3923 instead of the 392399. 这应该读取前4个字节,并提取文件大小信息,但它返回3923而不是392399。

as the file size... what happened? 作为文件大小...发生了什么事? "392399" should be able to fit into 4 bytes. “ 392399”应该能够容纳4个字节。

We are suppose to be using big endian. 我们假设正在使用大端。

This is because str(SIZE_OF_FILE) typesets the number using decimal notation - that is, you get the string "392399" , which is 6 characters (and 6 bytes in UTF-8). 这是因为str(SIZE_OF_FILE)使用十进制表示法键入数字-即,您将获得字符串"392399" ,该字符串为6个字符(在UTF-8中为6个字节)。 If you send only the first 4, you are sending "3923" . 如果仅发送前4个,则发送"3923"

What you probably want to do is use something like struct.pack to create a bytestring containing the binary representation of the number. 您可能想要做的是使用struct.pack类的struct.pack来创建一个包含数字二进制表示形式的字节struct.pack

s.send(struct.pack(format_string, SIZE_OF_FILE))

You are sending the size as a string ( "392399" ), which is 6 ASCII characters and therefore 6 bytes. 您将以字符串( "392399" )的形式发送大小,它是6个ASCII字符,因此是6个字节。 You want to send it as a raw integer; 您想将其作为原始整数发送; use struct.pack to do that: 使用struct.pack来做到这一点:

s.send(struct.pack(">i", SIZE_OF_FILE))

To recieve: 接收:

fileSize = struct.unpack(">i", conn.recv(4))[0]

The > makes it big-endian. >使它成为大端。 To make it little-endian, use < instead. 要使其为小端,请使用<代替。 i is the type; i是类型; in this case, a 4-byte integer. 在这种情况下,为4字节整数。 The linked documentation has a list of types, in case you want to use another one. 链接的文档中列出了类型,以防您想使用其他类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM