stomp协议

本文介绍了STOMP协议,一种在消息框架中用于通信的文本协议,其结构类似HTTP,支持跨平台互操作。详细讲解了STOMP的命令,包括SEND、SUBSCRIBE等,并提及其实现。

stomp协议简介

stomp协议是消息框架中的通信协议
通信格式是文本结构类似于HTTP
可以互操作

stomp文本结构

COMMAND
header1:value1
header2:value2

Body^@

命令

SEND
SUBSCRIBE
UNSUBSCRIBE
BEGIN
COMMIT
ABORT
ACK
NACK
DISCONNECT

实现

# -*- coding:utf-8 -*-

import traceback
import gevent
from gevent import socket
from gevent.pool import Pool


class Stomp(object):
    def __init__(self, host, port, username, password):
        self.username = username
        self.password = password
        self.host = host
        self.port = port
        self.pool = Pool(3)
        self.connecting = False
        self._connect_auth()
        hb = self.pool.spawn(self._heart_beating)
        self.pool.start(hb)
    #连接
    def _connect_auth(self):
        print "re auth "
        self.sock = socket.create_connection((self.host, self.port))
        self._command(command="CONNECT", headers={"login": self.username, "passcode": self.password}, body="")
        self.connecting = True
    #心跳,断线重连
    def _heart_beating(self):
        while True:
            print "_heart_beating"
            try:
                if not self.connecting:
                    self._connect_auth()
                self._command(command="CONNECT", headers={"heart-beat":"0,60"}, body="")
                self.connecting = True
                gevent.sleep(30)
            except:
                print traceback.format_exc()
                self.connecting = False
    #发送请求
    def _command(self, command, headers, body):
        new_headers = {}
        new_headers.update(headers)
        frame = self.to_string(command, headers, body)
        self.sock.send(frame)

    #格式化请求,返回Frame
    def to_string(self, command, headers, body):
        header_list = [k + ":" + v + "\n" for k, v in headers.items()]
        headers_line = "".join(header_list)
        frame_string = command + "\n" + headers_line + "\n" + body + "\x00"
        return frame_string

    def send(self, headers, body):
        gl = self.pool.spawn(self._command,"SEND",headers, body)
        self.pool.start(gl)


    def dis_connect(self):
        gevent.sleep(5)
        self.sock.close()
        self.pool.kill()

这是协议文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值