Flutter使用WebSockets

发布于 19 天前 作者 magege666 64 次浏览 最后一次编辑是 19 天前 来自 分享

注意是WebSockets而不是 socket.io

文档:https://flutter.dev/docs/cookbook/networking/web-sockets

安装

dependencies:
  web_socket_channel:

**Flutter **

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:web_socket_channel/io.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final channel = IOWebSocketChannel.connect('ws://192.168.0.101:8080');

  @override
  void dispose() {
    channel.sink.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Page'),
      ),
      body: Center(
        child: StreamBuilder(
          stream: channel.stream,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.active) {
              print(snapshot.data); // {"event":"events","data":"hello i'm Nestjs"}
              return Container(
                width: double.infinity,
                height: 200,
                child: Center(
                  child: Text('${snapshot.data}'),
                ),
              );
            }
            return SizedBox();
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _sendMessage,
        tooltip: 'Send message',
        child: Icon(Icons.send),
      ), //
    );
  }
  
  /// 向服务器发送数据
  void _sendMessage() {
    print('send event!');
    channel.sink.add(
      jsonEncode(
        {
          "event": 'events',
          'data': 'Hi i\'m Flutter',
        },
      ),
    );
  }
}

server 这里使用Nestjs

import {
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  WsResponse,
} from '@nestjs/websockets';
import { of, Observable } from 'rxjs';
import { Server } from 'ws';

@WebSocketGateway(8080)
export class EventsGateway {
  @WebSocketServer()
  server: Server;

  @SubscribeMessage('events')
  onEvent(client: any, data: any): Observable<WsResponse<string>> {
    console.log(data); // Hi i'm Flutter
    return of({ event: 'events', data: "hello i'm Nestjs" });
  }
}
回到顶部