// 开始符号和结束符号分别为 '##' 和 '%%', 分隔符为 &&
|
// 开始符号
|
const startStr = '##';
|
// 分隔符号
|
const splitStr = '&&';
|
// 结束符号
|
const endStr = '%%';
|
// 校验格式
|
function verificationMessage(message) {
|
if (!message || message == '') {
|
return false;
|
}
|
if (!(typeof message == 'string')) {
|
return false;
|
}
|
if (!message.startsWith(startStr)) {
|
return false;
|
}
|
if (!message.endsWith(endStr)) {
|
return false;
|
}
|
return true;
|
}
|
/**
|
* 解析出类型和内容
|
* @param {*} message socket消息中的data字段
|
* @returns
|
*/
|
function decodeMessage(message) {
|
if (!verificationMessage(message)) {
|
return;
|
}
|
const parts = message.slice(startStr.length, -endStr.length).split(splitStr);
|
const type = parts[0];
|
let data = JSON.parse(parts[1]);
|
return {
|
type: type,
|
data: data
|
};
|
}
|
/**
|
* 生成指定格式的消息字符串
|
* @param {*} type 消息类型
|
* @param {*} data 消息内容
|
* @returns 生成的消息字符串
|
*/
|
function encodeMessage(type, data) {
|
return `${startStr}${type}${splitStr}${JSON.stringify(data)}${endStr}`;
|
}
|
|
export { verificationMessage, decodeMessage, encodeMessage };
|