1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// 开始符号和结束符号分别为 '##' 和 '%%', 分隔符为 &&
// 开始符号
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 };