Flutter开发进阶之使用Socket实现主机服务(二)
Flutter开发进阶之使用Socket实现主机服务(一)
在完成局域网内设备定位后就可以进入微服务的实操了。
I、构建Socket连接池
一、定义Socket
使用socket_io_client
socket_io_client: ^2.0.3+1
导入头文件
import 'package:socket_io_client/socket_io_client.dart' as io;
定义属性
class _SocketIoObject {/// 连接io.Socket? socket; /// 连接次数int count = 0; /// 创建的时间int createTime = 0; /// 根据连接频率获取的优先级double proportion = 0;
}
二、定义连接池
class SocketIoPool {/// 连接池本身static Map<String, dynamic> sockets = {}; /// 连接最大数量static int maxCount = 10; /// 根据优先级获取到/// 最应该销毁的连接的keystatic String exitKey = "";
}
三、连接池运行逻辑
连接排序
/// 将连接按照优先级排序
/// 使用频率越低的连接的优先级越高
/// 可以被销毁
///
static void _sortSocket() {int now = DateTime.now().millisecondsSinceEpoch;double maxProportion = 0;sockets.forEach((key, value) {value.proportion = (now - value.createTime) / value.count;if (value.proportion > maxProportion) {maxProportion = value.proportion;exitKey = key;}});}
连接创建
/// 创建新连接时限制最大连接数量
///
static io.Socket _newSocket(String host, int port) {if (sockets.length >= maxCount && exitKey.isNotEmpty) {_SocketIoObject? object = sockets[exitKey];if (object != null) {object.socket?.disconnect();object.socket?.dispose();sockets.remove(exitKey);}}String relative = "$host:$port";io.Socket socket = io.io(relative);sockets[relative] = _SocketIoObject()..socket = socket..count = 1..createTime = DateTime.now().millisecondsSinceEpoch;Future(() => _sortSocket());