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
import 'dart:convert';
class SocketMessageBody {
/// 1 : pong 2: 关闭连接 3:业务消息
int type;
/// 消息内容
dynamic content;
SocketMessageBody({required this.type, required this.content});
// 将 Message 对象转换为 Map
Map<String, dynamic> toMap() {
return {
'type': type,
'content': content,
};
}
// 从 Map 创建 Message 对象
factory SocketMessageBody.fromMap(Map<String, dynamic>? map) {
return SocketMessageBody(
type: map?['type'],
content: map?['content'] ?? '',
);
}
// 将 Message 对象转换为 JSON 字符串
String toJson() {
return jsonEncode(toMap());
}
// 从 JSON 字符串创建 Message 对象
factory SocketMessageBody.fromJson(String source) {
return SocketMessageBody.fromMap(jsonDecode(source));
}
@override
String toString() {
return 'Message(type: $type, content: $content)';
}
}