Dart:等待WebSocket响应

ars1skjm  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(173)

在我的代码中,我通过WebSocket建立了一个服务器连接。现在有一种情况,服务器响应我的消息,我想处理这个响应。但是,我找不到一个好的方法来解决这个问题。
我的方法是通过listen方法将来自WebSocket的响应写入一个列表,并在发送后查询这个列表(请参阅代码)。我在一个循环中多次调用sendAndWaitForAnswer方法,因为我必须向服务器发送几个请求以进行初始化。问题是WebSocket只有在sendAndWaitForAnswer已经被超时终止后才将答案写入rxData(参见输出)。有没有人知道如何等待WebSocket的答案?
我知道普通的HTTP请求可能会更好,因为你会直接得到响应,但不幸的是我不能改变服务器。
它不是一个Flutter应用程序。
打印输出:

send data and wait for response
send data and wait for response
send data and wait for response
send data and wait for response
send data and wait for response
new webSocket Message: ...     // event message simplified with "..."
new webSocket Message: ...
new webSocket Message: ...
new webSocket Message: ...
new webSocket Message: ...

我想要的:

send data and wait for response
new webSocket Message: ...
data found
send data and wait for response
new webSocket Message: ...
data found
send data and wait for response
new webSocket Message: ...
data found
send data and wait for response
new webSocket Message: ...
data found

简化代码:

class Connection {

    late IOWebSocketChannel webSocketChannel;
    var rxData = [];

    connect() {    
        webSocketChannel = IOWebSocketChannel.connect(  
            Uri.parse("ipAdress"),  
            pingInterval: Duration(seconds: 30),  
        );  
      
        webSocketChannel.stream.listen((event) {  
            print("new webSocket Message: $event");  
            rxData.add(event);  
        });   
    }

    send(opcode, parameters) {  
        Map<String, dynamic> dataSendMap = {  
            "opcode": opcode,  
            "parameters": parameters,  
        };  
        String jsonData = json.encode(dataSendMap);  
        webSocketChannel.sink.add(jsonData);  
    }

    sendAndWaitForAnswer(dataOpt, dataParam) {
        print("send data and wait for response");
        send(dataOpt, dataParam);
        timeout = 5;
        int startTime = DateTime.now().millisecondsSinceEpoch ~/ Duration.millisecondsPerSecond;
        while((DateTime.now().millisecondsSinceEpoch ~/ Duration.millisecondsPerSecond) - startTime < timeout) {
            for (var data in rxData) {  
                if (data['opcode'] == dataOpt) {  
                    print("data found");
                    answer = data;  
                    rxData.remove(data);  
                }  
            }
        }
        return answer;
    }
}
cpjpxq1n

cpjpxq1n1#

要在Dart中处理WebSocket响应,您可以使用web_socket_channel包,它提供了一种建立WebSocket连接和处理传入消息的便捷方法。以下是如何处理WebSocket响应的示例:

import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:web_socket_channel/io.dart'; 
class MyWebSocketWidget extends StatefulWidget {
  @override
  _MyWebSocketWidgetState createState() => _MyWebSocketWidgetState();
}

class _MyWebSocketWidgetState extends State<MyWebSocketWidget> {
  final channel = IOWebSocketChannel.connect('wss://your-websocket-url.com');

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('WebSocket Demo'),
      ),
      body: StreamBuilder(
        stream: channel.stream,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            // Process the received data
            final response = snapshot.data as String;
            // Do something with the response
            // ...
          }
          return Center(
            child: CircularProgressIndicator(),
          );
        },
      ),
    );
  }
}

相关问题