Android平台使用CoAP通信绑定设备已在前文中介绍,目前需要从Android平台迁移到Linux平台,flutter提供的CoAP协议包只提供了客户端而没有服务端,在进行设备绑定时,设备不仅要作为服务端,也要作为客户端接收底层的消息推送,尝试实现socket+udp通信模块。
class SocketUDPUtils {
String _localIP = '127.0.0.1'; //本机局域网IP
int _serverPort = 7583; //本机服务器端口,监听消息
int _destinationPort = 8888; //发送目的地端口,发送消息
late RawDatagramSocket _bindSocket;
static var mStream;
/// 单例模式
// 单例对象
static late final SocketUDPUtils _instance;
//内部构造方法,可避免外部暴露构造函数,进行实例化
SocketUDPUtils._internal();
//工厂构造方法,使用命名构造函数进行声明
factory SocketUDPUtils.getInstance() => _getInstance();
//获取单例内部方法
static _getInstance(){
//只能有一个实例
if(_instance == null){
_instance = SocketUDPUtils._internal();
}
return _instance;
}
// socket事件
void onSocketData(RawSocketEvent e) {
switch (e) {
//read 接收事件
case RawSocketEvent.read:
{
Datagram? dg = _bindSocket.receive();
if (dg != null) {
print('----[socket utils]----' + utf8.decode(dg.data));
var data = json.decode(utf8.decode(dg.data)); // 将UTF8数据解码
print('----[socket utils]----jsonDecode: $data');
BindReceiveBean msg = BindReceiveBean.fromJson(data);
print(
'----[socket utils]----收到来自${dg.address.toString()}:${dg.port}的数据:${dg.data.lengthInBytes}字节数据 ');
}
}
break;
//write 发送事件
case RawSocketEvent.write:
{
print('RawSocketEvent.write');
}
break;
case RawSocketEvent.readClosed:
{
print('RawSocketEvent.readClosed');
}
break;
case RawSocketEvent.closed:
{
print('RawSocketEvent.closed');
}
break;
}
}
// socket关闭
void onSocketDone() {
_bindSocket.close();
print('----[socket utils]----socket关闭');
}
// socket错误
void onSocketError(Object error) {
print('----[socket utils]----socket出现错误,error=${error.toString()}');
}
void waitUDPMsg() async {
_bindSocket = await RawDatagramSocket.bind(_localIP, _serverPort);
_bindSocket.readEventsEnabled = true;
mStream = _bindSocket.asBroadcastStream();
/// 监听套接字事件
mStream.listen(onSocketData, onError: onSocketError, onDone: onSocketDone);
}
void sendUDPMsg(BindSendBean msg) async {
RawDatagramSocket _rawSocket =
await RawDatagramSocket.bind(_localIP, _serverPort);
_rawSocket.send(utf8.encode(json.encode(msg.toJson())),
InternetAddress(_localIP), _destinationPort);
print(
'----[socket utils]----发送至$_localIP:$_destinationPort的数据:内容:${msg.toJson()}');
_rawSocket.close();
}
}
网友评论