ZLMediaKit/src/Http/WebSocketSplitter.h

101 lines
2.6 KiB
C
Raw Normal View History

2018-09-21 18:48:35 +08:00
//
2018-09-21 16:11:09 +08:00
// Created by xzl on 2018/9/21.
//
#ifndef ZLMEDIAKIT_WEBSOCKETSPLITTER_H
#define ZLMEDIAKIT_WEBSOCKETSPLITTER_H
#include <cstdint>
#include <string>
#include <vector>
#include <memory>
using namespace std;
class WebSocketHeader {
public:
typedef std::shared_ptr<WebSocketHeader> Ptr;
typedef enum {
CONTINUATION = 0x0,
TEXT = 0x1,
BINARY = 0x2,
RSV3 = 0x3,
RSV4 = 0x4,
RSV5 = 0x5,
RSV6 = 0x6,
RSV7 = 0x7,
CLOSE = 0x8,
PING = 0x9,
PONG = 0xA,
CONTROL_RSVB = 0xB,
CONTROL_RSVC = 0xC,
CONTROL_RSVD = 0xD,
CONTROL_RSVE = 0xE,
CONTROL_RSVF = 0xF
} Type;
2018-09-21 18:48:35 +08:00
public:
WebSocketHeader() : _mask(4){}
virtual ~WebSocketHeader(){}
2018-09-21 16:11:09 +08:00
public:
bool _fin;
uint8_t _reserved;
Type _opcode;
bool _mask_flag;
uint64_t _playload_len;
vector<uint8_t > _mask;
};
class WebSocketSplitter : public WebSocketHeader{
public:
WebSocketSplitter(){}
virtual ~WebSocketSplitter(){}
2018-09-21 18:48:35 +08:00
/**
* 便webSocket数据以及处理粘包问题
* onWebSocketDecodeHeader和onWebSocketDecodePlayload回调
* @param data
* @param len
*/
2018-09-21 16:11:09 +08:00
void decode(uint8_t *data,uint64_t len);
2018-09-21 18:48:35 +08:00
/**
*
* 2onWebSocketEncodeData回调
*
* @param data
* @param len
*/
2018-09-21 16:11:09 +08:00
void encode(uint8_t *data,uint64_t len);
protected:
2018-09-21 18:48:35 +08:00
/**
* webSocket数据包包头onWebSocketDecodePlayload回调
* @param packet
*/
virtual void onWebSocketDecodeHeader(const WebSocketHeader &packet) {};
/**
* webSocket数据包负载
* @param packet
* @param ptr
* @param len
* @param recved packet._playload_len时则接受完毕
*/
virtual void onWebSocketDecodePlayload(const WebSocketHeader &packet, const uint8_t *ptr, uint64_t len, uint64_t recved) {};
/**
* websocket数据编码回调
* @param ptr
* @param len
*/
virtual void onWebSocketEncodeData(const uint8_t *ptr,uint64_t len){};
2018-09-21 16:11:09 +08:00
private:
void onPlayloadData(uint8_t *data,uint64_t len);
private:
string _remain_data;
int _mask_offset = 0;
bool _got_header = false;
uint64_t _playload_offset = 0;
};
#endif //ZLMEDIAKIT_WEBSOCKETSPLITTER_H