Flutter WebSocket

  • Post author:
  • Post category:其他




Flutter WebSocket



建立连接

WebSocketChannel channel=IOWebSocketChannel.connect(“ws://127.0.0.1:8888/listen”);



监听

channel.stream.listen(

(event) {


//event为websocket服务器返回的数据,这是异步数据,需要注意

print(event);

});



监听

StreamBuilder(

stream: widget.channel.stream,

builder: (context, snapshot) {


return Text(snapshot.hasData ? ‘${snapshot.data}’ : ‘’);

},

);



发送

channel.sink.add(“HelloWorld”); //数据为字符串类型



关闭连接

channel.sink.close();



生命周期函数

channel.stream.listen(

(event) {}, //监听服务器消息

onError: (error){}, //连接错误时调用

onDone: (){}, //关闭时调用

cancelOnError:true //设置错误时取消订阅

);

参考:

https://zhuanlan.zhihu.com/p/330541375



版权声明:本文为weixin_45834664原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。