【#文档大全网# 导语】以下是®文档大全网的小编为您整理的《websocket的python代码》,欢迎阅读!
用Python实现一个简单的WebSocket服务器
ubuntu下python2.76
windows Python 2.79, chrome37 firefox35通过
代码是在别人(cddn有人提问)基础上改的, 主要改动了parsedata和sendmessage这2个函数.
改代码参考下面了这段文档. 主要是第5条, 发送的数据长度分别是 8bit和 16bit和 64 bit(即 127, 65535,和2^64-1)三种情况 发送和收取是一样的, 例如
1.长度小于125时(由于使用126, 127用作标志位.)
2. 数据长度在128-65525之间时, Payload Length位设为126, 后面额外使用16bit表示长度(前面的126不再是长度的一部分)
3.数据长度在65526-2^64-1之间时, Payload Length位设为127, 后面额外使用64bit表示长度(前面的127不再是长度的一部分)
1. Fin (bit 0): determines if this is the last frame in the message. This would be set to 1 on the end of a series of frames, or in a single-frame message, it would be set to 1 as it is both the first and last frame.
2. RSV1, RSV2, RSV3 (bits 1-3): these three bits are reserved for websocket
extensions, and should be 0 unless a specific extension requires the use of any of these bytes.
3. Opcode (bits 4-7): these four bits deterimine the type of the frame. Control frames communicate WebSocket state, while non-control frames communicate data. The various types of codes include: 1. x0: continuation frame; this frame contains data that should be appended to 2. 3. 4. 5. 6. 7.
the previous frame
x1: text frame; this frame (and any following) contains text
x2: binary frame; this frame (and any following) contains binary data x3 - x7: non-control reserved frames; these are reserved for possible websocket extensions
x8: close frame; this frame should end the connection x9: ping frame xA: pong frame
8. xB - xF: control reserved frames
4. Mask (bit 8): this bit determines whether this specific frame uses a mask or not.
5. Payload Length (bits 9-15, or 16-31, or 16-79): these seven bytes determine the payload length. If the length is 126, the length is actually determined by bits 16 through 31 (that is, the following two bytes). If the length is 127, the length is actually determined by bits 16 through 79 (that is, the following eight bytes). 6. Masking Key (the following four bytes): this represents the mask, if the Mask bit is set to 1.
7. Payload Data (the following data): finally, the data. The payload data may be sent over multiple frames; we know the size of the entire message by the payload length that was sent, and can append data together to form a single message until we receive the message with the Fin flag. Each consecutive payload, if it exists, will contain the 0 “continuation frame” opcode.
服务器端代码(为方便阅读,请在下面地址中打开): https://code.csdn.net/snippets/603552
客户端 (测试了chrome37, firefox35): https://code.csdn.net/snippets/603552
参考:用Python实现一个简单的WebSocket服务器
由于使用125, 126, 127用作标志位.
说明:
原服务器端代码中176和177需要注销,不然会出错。
我不是原作者,只是文章的搬运工,目的只是想要获得这个悬赏任务的奖金,谢谢!
原作者博客地址:http://blog.csdn.net/jiht594/article/details/43764941#
本文来源:https://www.wddqxz.cn/1ecdd2d9aaea998fcd220e09.html