我面临着在用DART编写的Android应用程序和Python服务器之间建立连接的挑战.这款安卓应用程序运行在安卓模拟器上.

我成功地使用WebSocket建立了连接,但在使用UDP时遇到了困难.令人惊讶的是,没有错误消息.

下面是应用程序的部分Dart代码:

    final serverAddress = InternetAddress('10.0.2.15');
    const port = 50001;
    _clientSocket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, port);
    _clientSocket.send('Hello from Flutter'.codeUnits, serverAddress, port);

    _clientSocket.listen((RawSocketEvent event) {
      if (event == RawSocketEvent.read) {
        Datagram dg = _clientSocket.receive()!;
        String message = String.fromCharCodes(dg.data);
        print('Received message: $message');
      }
    });

以下是服务器代码:

import socket

localIP = "127.0.0.1"
print(localIP)

localPort = 50001
bufferSize = 1024

UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
UDPServerSocket.bind((localIP, localPort))
print("UDP server up and listening")

while True:
    bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
    message = bytesAddressPair[0]
    address = bytesAddressPair[1]

    clientMsg = "Message from Client:{}".format(message)
    clientIP = "Client IP Address:{}".format(address)

    print(f"{clientMsg}\n{clientIP}\n-----------------\n")

    # Sending a reply to the client
    replyMsg = f"Hello test agent, thanks for messaging!\n-----------------\n"
    UDPServerSocket.sendto(str.encode(replyMsg), address)

推荐答案

您必须做的第一件事是更改Python:

import socket

localIP = "127.0.0.1"

import socket

localIP = "0.0.0.0"

如果您在不同的机器上运行,这对您来说已经很好用了.

now if you run client and server on the same machine then you have 至 specify a different source port in dart

  final serverAddress = InternetAddress('10.0.2.15');
    const srcPort = 5011;
    const destPort = 50001;
    var clientSocket =
        await RawDatagramSocket.bind(InternetAddress.anyIPv4, srcPort);
    clientSocket.send('Hello from Flutter'.codeUnits, serverAddress, destPort);

    clientSocket.listen((RawSocketEvent event) {
      if (event == RawSocketEvent.read) {
        Datagram dg = clientSocket.receive()!;
        String message = String.fromCharCodes(dg.data);
        print('Received message: $message');
      }
    });

Python相关问答推荐

如何使用PyTest根据self 模拟具有副作用的属性

在Python中为变量的缺失值创建虚拟值

Pythind 11无法弄清楚如何访问tuple元素

替换字符串中的多个重叠子字符串

将jit与numpy linSpace函数一起使用时出错

try 在树叶 map 上应用覆盖磁贴

为什么带有dropna=False的groupby会阻止后续的MultiIndex.dropna()工作?

如何在python polars中停止otherate(),当使用when()表达式时?

给定高度约束的旋转角解析求解

mypy无法推断类型参数.List和Iterable的区别

什么是合并两个embrame的最佳方法,其中一个有日期范围,另一个有日期没有任何共享列?

需要帮助重新调整python fill_between与数据点

可以bcrypts AES—256 GCM加密损坏ZIP文件吗?

try 检索blob名称列表时出现错误填充错误""

在Docker容器(Alpine)上运行的Python应用程序中读取. accdb数据库

如何求相邻对序列中元素 Select 的最小代价

使用np.fft.fft2和cv2.dft重现相位谱.为什么结果并不相似呢?

如何为需要初始化的具体类实现依赖反转和接口分离?

Regex用于匹配Python中逗号分隔的AWS区域

如何在Python中从html页面中提取html链接?