ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Flutter WebSocket

2021-09-18 13:29:51  阅读:410  来源: 互联网

标签:web WebSocket socket package dart import Flutter channel


再开发过程中我们经常会使用到WebSocket,而插件库为我们提供了一个使用非常方便的插件

web_socket_channel

我们需要根据自己的Flutter 版本选择对应的即可

web_socket_channel: ^1.1.0

在pubspec.yaml中我们引入,然后pub get 一下

pub get

到此就完成插件的引用。下面就是使用了

官网的代码使用

import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:web_socket_channel/status.dart' as status;

main() async {
  var channel = IOWebSocketChannel.connect(Uri.parse('ws://localhost:1234'));

  channel.stream.listen((message) {
    channel.sink.add('received!');
    channel.sink.close(status.goingAway);
  });
}

下面是我对其进行了简单的封装

import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:jianfa/view/main/my/message/detail/MessageDetailSocket.dart';
import 'package:jianfa/widget/CustomDialog.dart';
import 'package:web_socket_channel/io.dart';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';


class WebSocketChannel {
  // 创建WebSocketChannel 单利,全局只有一个对象
  WebSocketChannel._privateConstructor();

  static final WebSocketChannel _instance =
      WebSocketChannel._privateConstructor();

  static WebSocketChannel get instance {
    return _instance;
  }
    
  BuildContext contexts;

  
  IOWebSocketChannel channel;
   
  // 开始进行链接
  void connect(BuildContext context) {
    contexts = context;
    channel = IOWebSocketChannel.connect(
        "ws://localhost:1234");
    sendMessage();
    channel.stream.listen(this.onData, one rror: one rror, onDone: onDone);
  }

  // 发送消息
  void sendMessage() {
    channel.sink.add("");
  }

  // 断连,然后执行重连
  onDone() {
    debugPrint("Socket is closed");
    channel = IOWebSocketChannel.connect(
        "ws://localhost:1234");
    channel.stream.listen(this.onData, one rror: one rror, onDone: onDone);
    (() async {});
  }
  
  // 错误日志
  one rror(err) {
    debugPrint(err.runtimeType.toString());
    WebSocketChannelException ex = err;
    debugPrint(ex.message);
  }

  // 接受数据,数据json字符串,然后转成Map
  onData(event) {
    print('收到消息:' + event);
    Map<String, dynamic> map = json.decode(event);
    
  }

  void dispose() {
    channel.sink.close();
  }
}

下面是使用

// 创建对象
WebSocketChannel webSocketChannel = WebSocketChannel.instance;

// 开始进行链接
webSocketChannel.connect(context);

// 断开链接
webSocketChannel.dispose();

到此就完成了web_socket_channel的简单封装和基本使用。

标签:web,WebSocket,socket,package,dart,import,Flutter,channel
来源: https://blog.csdn.net/WangQingLei0307/article/details/120365325

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有