结构体转字节流方案改进,用于传输视频流
#pragma once
#include <atlstr.h>
#include <map>
#define MaxReqLen 15
#define Cmd_rtsp 200 //"rtsp"
#define Cmd_replay 201 //"replay"
#define HkReqRtsp_cmds_Play "play"
#define HkReqRtsp_cmds_Stop "stop"
#define HkReqRtsp_resolution_480 "640x480"
enum {
Err_cmd_replay_openFile = 100, //回放文件打开失败
Err_cmd_rtsp_open , //实时流打开失败
};
static std::map<int, CString> g_errHk{
{Err_cmd_replay_openFile,"回放文件打开失败"},
{Err_cmd_rtsp_open,"实时流打开失败"},
};
enum {
HkReqRtsp_null,
HkReqRtsp_indexCode,
HkReqRtsp_port,
HkReqRtsp_cmd,
HkReqRtsp_resolution,
HkReqRtsp_stream,
HkReqRtsp_end,
};
struct HkReqRtsp {
CString data[MaxReqLen] = { ""};
CString rstBuff = "";
int total = 0;
CString* getDatas() {
return data;
}
void setStream(const char* buff, int lenth)
{
data[HkReqRtsp_stream] = "";
char len[4]{ 0 };
int writeLenth = 4 + lenth + 1;
memcpy(&len[0], &writeLenth, sizeof(int));
for (int i = 0; i < 4; i++) //head
{
data[HkReqRtsp_stream].AppendChar(len[i]);
}
for (int i = 0; i < lenth; i++) //body
{
data[HkReqRtsp_stream].AppendChar(buff[i]);
}
data[HkReqRtsp_stream].AppendChar(0); //+1
}
int getStreamLenth()
{
int lenth = 0;
memcpy(&lenth, data[HkReqRtsp_stream], sizeof(int));
return lenth;
}
const char* getStreamHeader()
{
return data[HkReqRtsp_stream];
}
void toStruct(const char* buff, int buffLen) {
total = buffLen;
int index = 0;
int readLen = 0;
for (auto i = 0; i < HkReqRtsp_stream; i++)
{
int lenth = 0;
memcpy(&lenth, &buff[index], sizeof(int)); //head
readLen += 4;
index += sizeof(int);
data[i].Append(&buff[index], lenth); //data string
index += lenth;
readLen += lenth;
}
int lenth = buffLen - readLen;
if (lenth > 0)
{
data[HkReqRtsp_stream] = "";
int ck = 0;
memcpy(&ck, &buff[readLen], sizeof(int)); //head
if (ck != lenth)
{
return;
}
for (int j = 0; j < lenth; j++) //data byte
{
data[HkReqRtsp_stream].AppendChar(buff[readLen+j]);
}
}
}
int getTotal() {
return total;
}
const char* toChars() {
total = 0;
rstBuff = "";
for (auto i = 0; i < HkReqRtsp_stream; i++)
{
char len[4]{ 0 };
int lenth = data[i].GetLength();
total += lenth;
memcpy(&len[0], &lenth, sizeof(int));
total += 4;
for (int i = 0; i < 4; i++) //head
{
rstBuff.AppendChar(len[i]);
}
rstBuff.Append(data[i]); //data string
}
total += getStreamLenth();
for (int j = 0; j < getStreamLenth(); j++) //data byte
{
rstBuff.AppendChar(data[HkReqRtsp_stream][j]);
}
return rstBuff;
}
};
//decodeStream(req.getStreamHeader()+sizeof(int), req.getStreamLenth()- sizeof(int) -1);*/
同方案一理念相同,不同指出在于处理结构体的转换方式。
toChars 将CString 数组转换为 单个字符串
toStruct 将 单个字符串转换为CString 数组
对于视频流的二进制数据通过 setStream 来处理写入,在读取时 使用类似decodeStream(req.getStreamHeader()+sizeof(int), req.getStreamLenth()- sizeof(int) -1); 的方式来读取视频流