我正在尝试使用UDP协议在NodeMCU(在Arduino IDE中编程)和Android上的Unity应用之间交换数据。为此微控制器编写的脚本运行良好,可以正确发送和接收,我已经使用PacketSender对其进行了测试。它还可以正确接收从Unity应用发送的数据并将其打印在串行监视器上。但是,当我尝试在计算机上接收答复数据时,它不起作用。每个数据包都由计算机接收(通过WireShark检查),但看起来好像不是Unity所收到的。最奇怪的是,此应用在Android上运行时可以正确接收数据,但是很难调试。好像PC上有阻塞(?)的微控制器数据包(Unity应用从PacketSender获取正确的数据)。可能是由防火墙设置或类似原因引起的吗? 这是我要接收的Unity代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UnityEngine.UI;
using System;
using System.Text;
public class UDPTransmiter : MonoBehaviour {
static readonly object lockObject=new object();
UdpClient udpReceive;
Thread thread;
IPEndPoint endpoint;
public string ipAddress;
public int portValue;
string returnData;
bool dataAviable=false;
void Start () {
if (sPort != null) {
portValue = int.Parse (sPort.GetComponent<InputField> ().text);
}
if (ip != null)
ipAddress = ip.GetComponent<InputField> ().text;
thread = new Thread (new ThreadStart (Receive));
thread.Start ();
}
// Update is called once per frame
void Update () {
if (dataAviable) {
lock (lockObject) {
//process data
}
}
}
public bool isDataAviable(){
return dataAviable;
}
void OnApplicationQuit(){
if(thread!=null)thread.Abort ();
udpReceive.Close ();
}
public void EstablishConnection(){
endpoint = new IPEndPoint (IPAddress.Parse (ipAddress), portValue);
if (udpReceive != null)
udpReceive.Close ();
udpReceive = new UdpClient (portValue);
}
public void Receive(){
udpReceive = new UdpClient (portValue);
IPEndPoint tmp = new IPEndPoint (IPAddress.Any,0);
while (true) {
Debug.Log ("Receiving");
byte[] data = udpReceive.Receive (ref tmp);
lock (lockObject) {
returnData = Encoding.ASCII.GetString (data);
Debug.Log ("Data: " + returnData);
dataAviable = true;
}
}
}
}