20

I'm looking to script some basic requests over the SPDY protocol. The protocol defines the frames you send as being comprised of binary data of very specific length and byte order.

I've only ever written small programs that send strings across sockets (HTTP). How do I go about implementing a SPDY control frame header for example? I've tried using the bitstring library and numpy to control the size of all the different sections of a control frame header for example but nothing is really working. The current SPDY library for python uses cython and C data types and i've found it to be very unpredictable. I was wondering how I can go about building simple requests with pure python or very simply how do I go about building something precisely like the protocol defines and sending it across a socket?

4

2 回答 2

29

一般来说bytearray,班级将是你的朋友(如果我正确理解你的问题)。您可以通过套接字发送它:

my_bytes = bytearray()
my_bytes.append(123)
my_bytes.append(125)

// my_bytes is b'{}' now

s.send(my_bytes)

遵循协议规范并逐字节创建。这在您接收数据时也有效:

data = s.recv(2048)
my_bytes = bytearray(data)

我对 SPDY 协议了解不多,但例如控制位是消息中的第一位(不是字节)。您可以通过二进制 AND 检索它my_bytes,例如:

control_frame = my_bytes[0] & 128

这是因为128它是10000000二进制的,因此二进制 AND 只会给你第一位(请记住,每个字节有 8 位,这就是我们有 7 个零的原因)。

事情就是这样手动完成的。当然,我建议使用一些库,因为编写适当的协议处理程序将花费大量时间,您可能会发现它非常困难并且可能效率不高(当然取决于您的需求)。

于 2013-08-19T10:04:23.657 回答
3

也可以使用struct 模块用字符串定义头部格式并直接解析。

要生成数据包:

fmt = 'B I 4b'
your_binary_data = pack(fmt, header_data)
sock.sendall(your_binary_data)

其中fmt指示标头格式(例如,'BI 4b' 只是一个,显然不适用于您的 SPDY 标头)。不幸的是,您将不得不处理非字节对齐的标头字段,可能是通过解析更大的块然后根据您的格式划分它们。

除此之外,解析标题:

unpacker = struct.Struct('B I 4b')
unpacked_data = unpacker.unpack(s.recv(unpacker.size))

unpacked_data将包含一个带有解析数据的元组。

struct 模块执行 Python 值和表示为 Python 字符串的 C 结构之间的转换。我不能保证这种方法的效率,但它帮助我通过调整fmt字符串来解析不同的协议。

于 2018-01-17T16:00:56.807 回答