socket_message.dart 925 Bytes
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)';
  }
}