美文网首页Flutter开发圈
flutter通过websocket接收go后台数据

flutter通过websocket接收go后台数据

作者: 渣渣曦 | 来源:发表于2019-03-04 20:16 被阅读355次

1、pubspec文件管理Flutter应用程序的assets(资源,如图片、package等)。 在pubspec.yaml中,通过网址“https://pub.dartlang.org/packages/web_socket_channel”确认版本号后,将web_socket_channel (1.0.9或更高版本)添加到依赖项列表;通过网址“https://pub.dartlang.org/packages/charts_flutter”确认版本号后,将charts_flutter(0.6.0或更高版本)添加到依赖项列表。

2、在Android Studio的编辑器视图中查看pubspec时,单击右上角的 Packages get,或者在命令行输入“flutter packages get”;这会将依赖包安装到您的项目。

3、运行以下代码:

import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page',
          channel: new IOWebSocketChannel.connect('ws://192.168.31.157/echo')),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;
  final WebSocketChannel channel;

  MyHomePage({Key key,this.title,this.channel}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class ClicksPerYear {
  final String year;
  final int clicks;
  final charts.Color color;

  ClicksPerYear(this.year, this.clicks, Color color)
      : this.color = new charts.Color(
      r: color.red, g: color.green, b: color.blue, a: color.alpha);
}


class TimeSeriesSales {
  final DateTime time;
  final int sales;

  TimeSeriesSales(this.time, this.sales);
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 4;

  final serialdata = [
    new TimeSeriesSales(new DateTime(2017, 9, 1), 5),
    new TimeSeriesSales(new DateTime(2017, 9, 2), 25),
    new TimeSeriesSales(new DateTime(2017, 9, 3), 100),
    new TimeSeriesSales(new DateTime(2017, 9, 4), 75),
  ];
  Random random = new Random();

  void _incrementCounter() {
    widget.channel.sink.add("request");
    widget.channel.stream.listen((data) {
    setState(() {
        _counter++;
        serialdata.add(new TimeSeriesSales(new DateTime(2017, 9, _counter), int.tryParse(data) ?? 0));
        if(serialdata.length>20) {
          serialdata.removeAt(0);
        }
    });
    });
  }

  @override
  Widget build(BuildContext context) {
    List<charts.Series<TimeSeriesSales, DateTime>> seriesList = [
      new charts.Series<TimeSeriesSales, DateTime>(
        id: 'Sales',
        colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
        domainFn: (TimeSeriesSales sales, _) => sales.time,
        measureFn: (TimeSeriesSales sales, _) => sales.sales,
        data: serialdata,
      )
    ];

    var chart = new charts.TimeSeriesChart(
      seriesList,
      animate: false,
    );
    var chartWidget = new Padding(
      padding: new EdgeInsets.all(32.0),
      child: new SizedBox(
        height: 200.0,
        child: chart,
      ),
    );

    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          children: <Widget>[
            chartWidget,
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ),
    );
  }
}

go代码如下:

// websockets.go
package main

import (
    "fmt"
    "html/template"
    "log"
    "math/rand"
    "net/http"
    "strconv"
    "time"

    "github.com/gorilla/mux"
    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {
        conn, _ := upgrader.Upgrade(w, r, nil) // error ignored for sake of simplicity

        for {
            // Read message from browser
            msgType, msg, err := conn.ReadMessage()
            if err != nil {
                return
            }

            // Print the message to the console
            fmt.Printf("%s sent: %s\n", conn.RemoteAddr(), string(msg))

            for i := 0; i < 10000; i++ {
                if err = conn.WriteMessage(msgType, []byte(strconv.Itoa(rand.Intn(100)))); err != nil {
                    return
                }
                time.Sleep(1 * time.Second)
            }
        }
    })

    router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        t, err := template.ParseFiles("websocket.html")
        if err != nil {
            log.Println("error", err)
        }
        err = t.Execute(w, map[string]interface{}{"departments": "departments"})
        if err != nil {
            log.Println("error", err)
        }
    })
    fmt.Println("websocket 80 端口启动")
    server := &http.Server{Addr: ":80", Handler: router}
    server.ListenAndServe()
}

运行效果如下图:


image.png

相关文章

网友评论

    本文标题:flutter通过websocket接收go后台数据

    本文链接:https://www.haomeiwen.com/subject/fudwuqtx.html