【问题标题】:Udp socket in Flutter does not receive anythingFlutter中的udp套接字没有收到任何东西
【发布时间】:2020-06-29 09:51:03
【问题描述】:

我正在尝试在 Flutter 中使用 udp 套接字作为服务器。我想将此套接字绑定到我的本地主机上的 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

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

谢谢!

【问题讨论】:

  • 如果你在“switch(e)”之前打印一些东西,你会看到一些东西吗?
  • 是的,打印效果很好
  • ok 尝试使用下面的代码,使用 udpSocket.receive()

标签: sockets flutter dart udp serversocket


【解决方案1】:

如果它可以帮助你,这里是我的应用程序中我的 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);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 2016-07-05
    • 2020-12-26
    • 2016-06-20
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多