流flutter时从流返回值
我有一个websocket流。我有一个名为sendMessage()的函数,该函数通过WebSocket发送消息并返回WebSocket服务器的请求。问题是我的功能正在返回空,因为在WebSocket的流已经完成之前返回。
- 不知道如何致电senmessage(),以便等待websocket 流将完成。
- websocket流才返回
不知道如何编写senmessage(),以便仅在我的代码中呼叫sendMessage()的
:字符串aux =等待sendmessage(jsonstring,device_ip,'199');
Future <String> sendMessage(msg, String ip, String port) async {
WebSocketChannel? channel;
// We use a try - catch statement, because the connection might fail.
try {
// Connect to our backend.
channel = WebSocketChannel.connect(Uri.parse('ws://${ip}:${port}'));
} catch (e) {
// If there is any error that might be because you need to use another connection.
print("Error on connecting to websocket: " + e.toString());
}
// Send message to backend
channel?.sink.add(msg);
String? aux;
// Listen for any message from backend
channel?.stream.listen((response) {
// Just making sure it is not empty
if (response!.isNotEmpty) {
// Now only close the connection and we are done here!
if(response!="Connected"){
aux=response;
channel!.sink.close();
}
}
}, onDone: () {
print("Stream done");});
return aux.toString();
}
I have a WebSocket stream. I have a function named sendMessage() that sends a message throug a websocket and returns the request of the websocket server. Problem is that my function is returning null because returns before websocket's streams has been completed.
- Don't know how to call senMessage() so that it waits for websocket
stream to be completed. - Don't know how to write senMessage() so that it returns only when websocket streams has been completed
Calling sendMessage() in my code:
String aux = await sendMessage(jsonString,device_ip,'199');
Future <String> sendMessage(msg, String ip, String port) async {
WebSocketChannel? channel;
// We use a try - catch statement, because the connection might fail.
try {
// Connect to our backend.
channel = WebSocketChannel.connect(Uri.parse('ws://${ip}:${port}'));
} catch (e) {
// If there is any error that might be because you need to use another connection.
print("Error on connecting to websocket: " + e.toString());
}
// Send message to backend
channel?.sink.add(msg);
String? aux;
// Listen for any message from backend
channel?.stream.listen((response) {
// Just making sure it is not empty
if (response!.isNotEmpty) {
// Now only close the connection and we are done here!
if(response!="Connected"){
aux=response;
channel!.sink.close();
}
}
}, onDone: () {
print("Stream done");});
return aux.toString();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须“等待”使用等待关键字的请求。而是这样做:
channel =等待websocketchannel.connect(uri.parse('ws:// $ {ip}:$ {port}'));
>You have to 'await' for the request to finish using the await keyword. Do this instead:
channel = await WebSocketChannel.connect(Uri.parse('ws://${ip}:${port}'));