Flutter 中的 Udp 套接字没有收到任何东西

Udp socket in Flutter does not receive anything

我正在尝试使用 udp 套接字作为 Flutter 中的服务器。我想将此套接字绑定到我本地主机上的 6868 端口,始终处于监听状态。不幸的是,当我尝试从客户端发送内容时,它从不打印字符串“RECEIVED”。 这是代码:

static Future openPortUdp(Share share) async {
        await RawDatagramSocket.bind(InternetAddress.anyIPv4,6868)
        .then(
          (RawDatagramSocket udpSocket) {
            udpSocket.listen((e) {
              switch (e) {
                case RawSocketEvent.read:
                  print("RECEIVED");
                  print(String.fromCharCodes(udpSocket.receive().data));
                  break;
                case RawSocketEvent.readClosed:
                    print("READCLOSED");
                    break;
                case RawSocketEvent.closed:
                  print("CLOSED");
                  break;
              }
            });
          },
        );
      }

我是不是做错了什么?

反正这是客户端,写的是Lua:

local udp1 = socket.udp()
while true do
    udp1:setpeername("192.168.1.24", 6868)
    udp1:send("HI")
    local data1 = udp1:receive()
    if (not data1 == nil) then print(data1) break end
    udp1:close()
end

我用另一台服务器对其进行了测试,它运行良好,所以我认为客户端没有问题。

谢谢!

如果它可以帮助你,这里是我的应用程序中的 SocketUDP(作为单例)代码。 我在 localhost 中使用它并且效果很好:

class SocketUDP {
  RawDatagramSocket _socket;

  // the port used by this socket
  int _port;

  // emit event when receive a new request. Emit the request
  StreamController<Request> _onRequestReceivedCtrl = StreamController<Request>.broadcast();

  // to give access of the Stream to listen when new request is received
  Stream<Request> get onRequestReceived => _onRequestReceivedCtrl.stream;

  // as singleton to maintain the connexion during the app life and be accessible everywhere
  static final SocketUDP _instance = SocketUDP._internal();

  factory SocketUDP() {
    return _instance;
  }

  SocketUDP._internal();

  void startSocket(int port) {

    _port = port;

    RawDatagramSocket.bind(InternetAddress.anyIPv4, _port)
        .then((RawDatagramSocket socket) {
      _socket = socket;
      // listen the request from server
      _socket.listen((e) {
        Datagram dg = _socket.receive();
        if (dg != null) {
          _onRequestReceivedCtrl.add(RequestConvert.decodeRequest(dg.data, dg.address));
        }
      });
    });
  }

  void send(Request requestToSend, {bool isBroadCast:false}) {

    _socket.broadcastEnabled = isBroadCast;

    final String requestEncoded = RequestConvert.encodeRequest(requestToSend);
     List<int> requestAsUTF8 = utf8.encode(requestEncoded);
    _socket.send(requestAsUTF8, requestToSend.address, _port);
  }
}