Flutter使用WebSockets
注意是
WebSockets
而不是socket.io
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
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" });
}
}