You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

139 lines
4.1 KiB

4 months ago
import 'dart:async';
import 'dart:convert';
4 months ago
import 'dart:core';
import 'dart:core';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:huixiang/im/Proto.dart';
import 'package:huixiang/im/database/message.dart';
import 'package:huixiang/im/out/auth.pb.dart';
import 'package:huixiang/im/out/message.pb.dart';
import 'package:huixiang/main.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SocketClient {
Socket _socket;
SharedPreferences shared;
connect() async {
shared = await SharedPreferences.getInstance();
4 months ago
await Socket.connect('192.168.10.129', 9090).then((value) {
debugPrint("socket-connect");
_socket = value;
_socket.listen((data) {
print(data);
print("socket-listen");
Proto proto = Proto.fromBytes(data);
4 months ago
MsgData dataResult = MsgData.fromBuffer(proto.body);
print('收到来自:${dataResult.from},消息内容: ${utf8.decode(dataResult.data)} ');
4 months ago
Map<String, dynamic> messageMap = createMessage(userId, utf8.decode(dataResult.data), msgType: dataResult.type.value, userId: dataResult.from);
Message message = Message.fromJson(messageMap);
callbacks[userId]?.call(message); /// user self conversation callback
callbacks[dataResult.from]?.call(message); /// user conversation callback
4 months ago
hxDatabase.insert(messageMap);
}, onError: (Object error, StackTrace stackTrace) {
4 months ago
debugPrint("socket-listen-error: $error, stackTrace: $stackTrace");
4 months ago
}, onDone: () {
debugPrint("socket-listen-down: down");
});
authRequest(shared.getString("token"));
4 months ago
heartbeat();
}).catchError((error) {
debugPrint("socket-connect-error: $error");
4 months ago
reconnectTime = 1500;
_socket = null;
4 months ago
reconnect();
});
}
4 months ago
heartbeat() {
Timer.periodic(const Duration(milliseconds: 30000), (timer) {
int milliseTime = DateTime.now().millisecondsSinceEpoch;
debugPrint("heartbeat: ${milliseTime}");
Uint8List data = utf8.encode(jsonEncode({"heartbeat": milliseTime}));
MsgData msgData = MsgData(from: userId, type: MsgType.TEXT, data: data);
final proto2 = Proto(3, 1, msgData.writeToBuffer());
4 months ago
_socket.add(proto2.toBytes());
});
}
4 months ago
int reconnectTime = 1500;
4 months ago
reconnect() {
Future.delayed(Duration(milliseconds: reconnectTime *= 2), () {
dispose();
connect();
});
}
Map<String, Function(Message message)> callbacks = <String, Function(Message message)>{};
addCallback(String userId, callback) {
callbacks[userId] = callback;
}
4 months ago
removeCallback(String userId) {
callbacks.remove(userId);
}
dispose() {
4 months ago
if (_socket != null) {
_socket.close();
_socket = null;
4 months ago
}
}
authRequest(String token) {
if (!checkSocket()) {
return;
}
final authReq = AuthReq()
4 months ago
..uid = userId
..token = token;
final authReqBytes = authReq.writeToBuffer();
final proto = Proto(1, 1, authReqBytes); // 假设 operation 和 seqId 为 1
final protoBytes = proto.toBytes();
_socket.add(protoBytes);
}
4 months ago
Future<Message> sendMessage(String toId, String content) async {
4 months ago
Map<String, dynamic> message = createMessage(toId, content, userId: userId);
4 months ago
int id = await hxDatabase.insert(message).catchError((error) {
debugPrint("insertMessage: $error");
});
if (!checkSocket()) {
4 months ago
hxDatabase.update({"id": id, "state": 3}).catchError((error) {
debugPrint("insertMessage: $error");
});
message["id"] = id;
message["state"] = 3;
return Message.fromJson(message);
}
4 months ago
message["id"] = id;
Uint8List data = utf8.encode(content);
4 months ago
MsgData msgData = MsgData(to: toId, from: userId, type: MsgType.TEXT, data: data);
final proto2 = Proto(5, 1, msgData.writeToBuffer());
_socket.add(proto2.toBytes());
4 months ago
debugPrint("sendMessage: ${message["id"]}");
return Message.fromJson(message);
}
checkSocket() {
if (_socket == null) {
4 months ago
reconnectTime = 1500;
4 months ago
reconnect();
return false;
}
return true;
}
4 months ago
String get userId => shared.getString("userId");
}