Flutter使用WebSockets的方法

发布于 8 天前 作者 sinazl 18 次浏览 最后一次编辑是 8 天前 来自 分享

install

dependencies:
  web_socket_channel:

demo

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**

**创建一个ws服务的工作示例**

events.gateway.ts

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" });
  }
}
回到顶部