= =!关于这些的资料真的少、我写一篇参考
(我也参考了github上一个前辈的代码https://github.com/akshayeshenoi/StompWS)前辈、如果介意请联系我、我立马删除
stomp是个协议、具体啥协议自己查。
stomp命令:
CONNECT
SEND
SUBSCRIBE
UNSUBSCRIBE
BEGIN
COMMIT
ABORT
ACK
NACK
DISCONNECT
websocket是个啥自己查
前提条件:服务器是webscoket、stomp协议的
实现思路:连接好websocket、
send:自己再把符合stomp协议的string 用websocket发出去
recv:while true websocket.recv()收到的东西用stomp进行解析
封装stomp报文的方法
BYTE = {
'LF': '\x0A',
'NULL': '\x00'
}
def _transmit(command, headers, msg=None):
"""
Marshalls and transmits the frame
"""
# Contruct the frame
lines = []
lines.append(command + BYTE['LF'])
# add headers
for key in headers:
lines.append(key + ":" + headers[key] + BYTE['LF'])
lines.append(BYTE['LF'])
# add message, if any
if msg is not None:
lines.append(msg)
# terminate with null octet
lines.append(BYTE['NULL'])
frame = ''.join(lines)
# transmit over ws
return frame
ws是webscoket连接实例
stomp–> conn
def conn_aps_stomp(ws, url):
headers = {}
headers['host'] = url
headers['accept-version'] = '1.2'
headers['heart-beat'] = '0,0'
ws.send(_transmit('CONNECT', headers))
stomp–>subscribe
def subscribe_aps_stomp(ws, destination, user_id):
"""
:param ws:
:param destination: str
:param user_id: str
:return:
"""
headers = {}
headers['id'] = user_id
headers['ack'] = 'client'
headers['destination'] = destination
ws.send(_transmit('SUBSCRIBE', headers))
stomp–>send message
def send(ws,destination, message):
"""
Transmit a SEND frame
"""
headers = {}
headers['destination'] = destination
headers['content-length'] = str(len(message))
ws.send(_transmit('SEND', headers, msg=message))
stomp–>解析函数
def _parse_message(frame):
"""
Returns:
command
headers
body
Args:
frame: raw frame string
"""
print fs_constant.FS_LOG_DEBUG + "will parse :" + frame
lines = frame.split(BYTE['LF'])
print fs_constant.FS_LOG_DEBUG + str(lines)
command = lines[0].strip()
headers = {}
# get all headers
i = 1
if i >= len(lines):
print fs_constant.FS_LOG_WARN + "data is 0 size:-|" + str(lines)
return command, headers, ''
while lines[i] != '':
# get key, value from raw header
(key, value) = lines[i].split(':')
headers[key] = value
i += 1
print fs_constant.FS_LOG_DEBUG + lines[i]
if i >= len(lines):
print "break parse----------->>>>>>>>>>"
break
# set body to None if there is no body
body = None if lines[i + 1] == BYTE['NULL'] else lines[i + 1]
return command, headers, body
处理返回
while True:
try:
info = ws.recv()
command, head, body = _parse_message(info)
# print command
# print head
# print body
# command还有好多、- -!根绝需要自行处理
if command == “MESSAGE”:
pass