flutter socket / websocket

fluuter socket

// ChangeNotifier 源自于 provider
class SocketManager extends ChangeNotifier {

  dynamic _data;
  get getData => _data;

  Socket? _clientSocket;
  StreamSubscription? _response;
  final String? host;
  final int port;
  final dynamic sourceAddress;
  final int sourcePort;

  // 构造方法
  SocketManager(this.host,{this.port = 0,this.sourceAddress,this.sourcePort = 0});

  // 私有
  void _connectSocket() async {
    _clientSocket = await Socket.connect(host, port,sourceAddress: sourceAddress,sourcePort: sourcePort); // 连接服务器
    _clientSocket?.timeout(const Duration(seconds: 3),onTimeout: (event){
      throw Exception('connect timeout for /*timeoutReconnect*/');
    });
  }

  void connectServer() async {
    _connectSocket();
  }

  void listenServer(){
    _response = utf8.decoder.bind(_clientSocket!).listen((data) {
        /* 接收数据 */
    });
    _response?.onDone(() { /* 完成一次监听 */});
    _response?.onError((error){ /* 错误信息 */});
  }

  void sendMsg(message) async {
    _clientSocket?.writeln(message); // 发送数据
  }

  void cancelResponse(){
    if (_response != null) _response!.cancel();
  }

  void timeoutReconnect(){
    _connectSocket();
  }

  void closeSocket(){
    _clientSocket?.close();
  }
}

注意:也可用三方包 socket_io_client

flutter websocket

结合 flutter_local_notifications

// ChangeNotifier 源自于 provider
class WebSocketManager extends ChangeNotifier {

  dynamic _data;
  get getData => _data;

  WebSocket? _clientSocket;
  StreamSubscription? _response;
  final String? url;
  final Iterable? protocols;
  final Map? headers;
  WebSocketManager(this.url,{this.protocols,this.headers});

  // 私有方法
  void _connectSocket() async {
    _clientSocket = await WebSocket?.connect(url!,protocols: protocols,headers: headers);
    _clientSocket?.timeout(const Duration(seconds: 3),onTimeout: (event){
      throw Exception('connect timeout for /*timeoutReconnect*/');
    });
  }

  void connectServer(){
    _connectSocket();
  }

  void listenServer(){

    _response = _clientSocket?.listen((data) {

    });
    _response?.onDone(() {});
    _response?.onError((error){});
  }

  void sendMsg(message){
    _clientSocket?.addStream(Stream.value(message));
  }
  void timeoutReconnect(){
    closeWebSocket();
    _connectSocket();
  }
  void closeWebSocket(){
    _clientSocket?.close();
  }

  // flutter_local_notifications
  void _pushNotification(object) async {
    await LocalNotifications.createNotification(object).then((value) => debugPrint('$value'));
  }

}

class LocalNotifications {

  static final FlutterLocalNotificationsPlugin _notification = FlutterLocalNotificationsPlugin();

  static Future createNotification(object) async {
    AndroidNotificationDetails androidDetails = AndroidNotificationDetails(
        object.id,
        object.title,
      channelDescription: object.content
    );
    DarwinNotificationDetails iosDetails = DarwinNotificationDetails(
      presentBadge: object.id,
      subtitle: object.title,
      attachments: object.content
    );
    // 发送通知
    NotificationDetails details = NotificationDetails(android:androidDetails ,iOS:iosDetails );
    await _notification.show(object.id, object.title, object.content, details);

    // 通知回调
    AndroidInitializationSettings ai = const AndroidInitializationSettings('@mipmap/ic_launcher');
    DarwinInitializationSettings ii = const DarwinInitializationSettings();
    InitializationSettings initSet = InitializationSettings(android: ai,iOS: ii);
    bool? inited = await _notification.initialize(initSet,
        onDidReceiveNotificationResponse: (
        NotificationResponse details){
          // app在前台点击通知事件响应
    },onDidReceiveBackgroundNotificationResponse: (
            NotificationResponse details) {
      // app在后台点击通知事件响应
        });
  }
}

你可能感兴趣的:(flutter socket / websocket)