C# esp8266和Unity之间的Udp连接问题

C# esp8266和Unity之间的Udp连接问题,c#,unity3d,arduino,udp,esp8266,C#,Unity3d,Arduino,Udp,Esp8266,我正在尝试将Wemos D1 mini ESP8266板连接到unity,以便向unity发送按钮状态 首先,我为Wemos D1 mini开发了代码,并使用UDP终端进行了检查,工作正常。我正在从终端向Wemos板发送一条消息,并在串行监视器上显示该消息 我正在发回一条带有按钮状态的消息,它显示在UDP终端上 然后我在Unity上编写了这段代码,并将其连接到主摄像头上,我在Wemos D1 mini上接收Unity发送的消息,但我无法读取Wemos发送的消息。我注意到,Socket.Avail

我正在尝试将Wemos D1 mini ESP8266板连接到unity,以便向unity发送按钮状态

首先,我为Wemos D1 mini开发了代码,并使用UDP终端进行了检查,工作正常。我正在从终端向Wemos板发送一条消息,并在串行监视器上显示该消息

我正在发回一条带有按钮状态的消息,它显示在UDP终端上

然后我在Unity上编写了这段代码,并将其连接到主摄像头上,我在Wemos D1 mini上接收Unity发送的消息,但我无法读取Wemos发送的消息。我注意到,
Socket.Available
始终为0

除了我没有阅读返回的消息之外,有时Unity也会崩溃(有时在我跑步时并不经常)。这是来自Arduino IDE的代码:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

//SSID of your network
char ssid[] = "TUI"; //SSID of your Wi-Fi router
char pass[] = "password"; //Password of your Wi-Fi router
int keyIndex = 0;

unsigned int localPort = 4000; 
char packetBuffer[255]; //buffer to hold incoming packet
char  ReplyBuffer[] = "";       // a string to send back

WiFiUDP Udp;

//input
const int buttonPin = 4;
const int ledpin = 5;
int buttonState = LOW;

void setup()
{
  pinMode(buttonPin, INPUT);
  pinMode(ledpin, OUTPUT);
  IPAddress ip(192, 175, 0, 20); 
  IPAddress gateway(192, 175, 0, 1); 
  IPAddress subnet(255, 255, 255, 0); 
  IPAddress DNS(192, 175, 0, 1); 
  Serial.begin(115200);
  WiFi.config(ip, gateway, subnet, DNS);  
  delay(100); 
  //WiFi.mode(WIFI_STA); 
  WiFi.begin(ssid, pass); 
  Serial.print("Connecting"); 
  while (WiFi.status() != WL_CONNECTED) { 
    Serial.print("."); 
    delay(200);  
  }   
  while (WiFi.waitForConnectResult() != WL_CONNECTED) { 
    Serial.println(); 
    Serial.println("Fail connecting"); 
    delay(5000); 
    ESP.restart(); 
  }   
  Serial.print("   OK  "); 
  Serial.print("Module IP: "); 
  Serial.println(WiFi.localIP());
  printWifiStatus(); 
  // if you get a connection, report back via serial:
  Udp.begin(localPort);
} 

void loop () {// if there's data available, read a packet
  int packetSize = Udp.parsePacket();

  if (packetSize) {
    Serial.print("Received packet of size ");
    Serial.println(packetSize);
    Serial.print("From ");
    IPAddress remoteIp = Udp.remoteIP();
    Serial.print(remoteIp);
    Serial.print(", port ");
    Serial.println(Udp.remotePort());

    // read the packet into packetBufffer
    int len = Udp.read(packetBuffer, 255);
    if (len > 0) {
      packetBuffer[len] = 0;
    }
    Serial.println("Contents:");
    Serial.println(packetBuffer);

    String str(packetBuffer);

    if(str == "hello from unity"){
      digitalWrite(ledpin, HIGH); 
    }

     buttonState = digitalRead(buttonPin);
     if(buttonState == HIGH){
      String str1 = "Button1 pressed"; 
      str1.toCharArray(ReplyBuffer, 50); 
     }
     else{
      String str1 = "Button1 off"; 
      str1.toCharArray(ReplyBuffer, 50);
     }

     Serial.println(ReplyBuffer);
     Serial.println(Udp.remoteIP());
     Serial.println(Udp.remotePort());

    // send a reply, to the IP address and port that sent the packet
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(ReplyBuffer);
    Udp.endPacket();
  }
  else{
      digitalWrite(ledpin, LOW);   
    }
    delay(10);
  }

解决了!必须更改c#中的接收代码并更新arduino代码,以便发送到端口4001(静态端口,因为我在接收随机端口上发送)

统一守则:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class esp8266Connection : MonoBehaviour {

    Thread m_Thread;
    UdpClient m_Client;


    void Start()
    {
        m_Thread = new Thread(new ThreadStart(ReceiveData));
        m_Thread.IsBackground = true;
        m_Thread.Start();
    }

    private void Update()
    {
        udpSend();
    }

    void ReceiveData()
    {

        try
        {

            m_Client = new UdpClient(4001);
            m_Client.EnableBroadcast = true;
            while (true)
            {

                IPEndPoint hostIP = new IPEndPoint(IPAddress.Any, 0);
                byte[] data = m_Client.Receive(ref hostIP);
                string returnData = Encoding.ASCII.GetString(data);

                Debug.Log(returnData);
            }
        }
        catch (Exception e)
        {
            Debug.Log(e);

            OnApplicationQuit();
        }
    }

    private void OnApplicationQuit()
    {
        if (m_Thread != null)
        {
            m_Thread.Abort();
        }

        if (m_Client != null)
        {
            m_Client.Close();
        }
    }
    void udpSend()
    {
        var IP = IPAddress.Parse("192.175.0.20");

        int port = 4000;


        var udpClient1 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        var sendEndPoint = new IPEndPoint(IP, port);


        try
        {

            //Sends a message to the host to which you have connected.
            byte[] sendBytes = Encoding.ASCII.GetBytes("hello from unity");

            udpClient1.SendTo(sendBytes, sendEndPoint);



        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
        }

    }
}
arduino的代码:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

//SSID of your network
char ssid[] = "TUI"; //SSID of your Wi-Fi router
char pass[] = "password"; //Password of your Wi-Fi router
int keyIndex = 0;

unsigned int localPort = 4000; 
char packetBuffer[255]; //buffer to hold incoming packet
char  ReplyBuffer[] = "";       // a string to send back

WiFiUDP Udp;

//input
const int buttonPin = 4;
const int ledpin = D1;
int buttonState = LOW;


void setup()
{
  pinMode(buttonPin, INPUT);
  pinMode(ledpin, OUTPUT);
  IPAddress ip(192, 175, 0, 20); 
  IPAddress gateway(192, 175, 0, 1); 
  IPAddress subnet(255, 255, 255, 0); 
  IPAddress DNS(192, 175, 0, 1); 
  Serial.begin(115200);
  WiFi.config(ip, gateway, subnet, DNS);  
  delay(100); 
  //WiFi.mode(WIFI_STA); 
  WiFi.begin(ssid, pass); 
  Serial.print("Connecting"); 
  while (WiFi.status() != WL_CONNECTED) { 
    Serial.print("."); 
    delay(200);  
  }   
  while (WiFi.waitForConnectResult() != WL_CONNECTED) { 
    Serial.println(); 
    Serial.println("Fail connecting"); 
    delay(5000); 
    ESP.restart(); 
  }   
  Serial.print("   OK  "); 
  Serial.print("Module IP: "); 
  Serial.println(WiFi.localIP());
  printWifiStatus(); 
  // if you get a connection, report back via serial:
  Udp.begin(localPort);
} 

void loop () {// if there's data available, read a packet
  int packetSize = Udp.parsePacket();

  if (packetSize) {
    Serial.print("Received packet of size ");
    Serial.println(packetSize);
    Serial.print("From ");
    IPAddress remoteIp = Udp.remoteIP();
    Serial.print(remoteIp);
    Serial.print(", port ");
    Serial.println(Udp.remotePort());

    // read the packet into packetBufffer
    int len = Udp.read(packetBuffer, 255);
    if (len > 0) {
      packetBuffer[len] = 0;
    }
    Serial.println("Contents:");
    Serial.println(packetBuffer);

    String str(packetBuffer);

    if(str == "hello from unity"){
      digitalWrite(ledpin, HIGH); 
    }


     buttonState = digitalRead(buttonPin);
     if(buttonState == HIGH){
      String str1 = "Button1 pressed"; 
      str1.toCharArray(ReplyBuffer, 50); 
     }
     else{
      String str1 = "Button1 off"; 
      str1.toCharArray(ReplyBuffer, 50);
     }

     Serial.println(ReplyBuffer);
      Serial.println(Udp.remoteIP());
      Serial.println(Udp.remotePort());


    // send a reply, to the IP address and port that sent the packet
    Udp.beginPacket(Udp.remoteIP(), 4001);
    Udp.write(ReplyBuffer);
    Udp.endPacket();
  }

  else{
      digitalWrite(ledpin, LOW);   
    }
    delay(10);
  }

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}
#包括
#包括
//您网络的SSID
字符ssid[]=“TUI”//您的Wi-Fi路由器的SSID
char pass[]=“密码”//您的Wi-Fi路由器的密码
int-keyIndex=0;
无符号int localPort=4000;
字符包缓冲区[255]//用于保存传入数据包的缓冲区
char ReplyBuffer[]=“”;//要发回的字符串
WiFiUDP-Udp;
//输入
const int buttonPin=4;
const int ledpin=D1;
int buttonState=低;
无效设置()
{
pinMode(按钮输入,输入);
引脚模式(LED引脚,输出);
ip地址ip(192,175,0,20);
IP地址网关(192、175、0、1);
IP地址子网(255、255、255、0);
IP地址DNS(192,175,0,1);
序列号开始(115200);
WiFi.config(ip、网关、子网、DNS);
延迟(100);
//WiFi.模式(WiFi_STA);
WiFi.begin(ssid,pass);
串行打印(“连接”);
而(WiFi.status()!=WL_已连接){
连续打印(“.”);
延迟(200);
}   
而(WiFi.waitForConnectResult()!=WL_已连接){
Serial.println();
Serial.println(“连接失败”);
延迟(5000);
特别是重新启动();
}   
串行打印(“OK”);
串行打印(“模块IP:”);
Serial.println(WiFi.localIP());
printWifiStatus();
//如果您获得连接,请通过串行方式报告:
开始(localPort);
} 
void loop(){//如果有可用数据,请读取数据包
int packetSize=Udp.parsePacket();
if(包装尺寸){
串行打印(“收到的大小数据包”);
序列号.println(包装尺寸);
连续打印(“从”);
IPAddress remoteIp=Udp.remoteIp();
串行打印(remoteIp);
串行打印(“端口”);
Serial.println(Udp.remotePort());
//把这个包读入packetbuffer
int len=Udp.read(packetBuffer,255);
如果(len>0){
packetBuffer[len]=0;
}
Serial.println(“目录:”);
Serial.println(packetBuffer);
字符串str(packetBuffer);
如果(str==“来自unity的你好”){
数字写入(ledpin,高电平);
}
buttonState=digitalRead(buttonPin);
如果(按钮状态==高){
字符串str1=“按下按钮1”;
str1.toCharArray(答复缓冲,50);
}
否则{
字符串str1=“按钮1关闭”;
str1.toCharArray(答复缓冲,50);
}
Serial.println(ReplyBuffer);
Serial.println(Udp.remoteIP());
Serial.println(Udp.remotePort());
//向发送数据包的IP地址和端口发送回复
Udp.beginPacket(Udp.remoteIP(),4001);
Udp.write(ReplyBuffer);
Udp.endPacket();
}
否则{
数字写入(ledpin,低电平);
}
延迟(10);
}
void printWifiStatus(){
//打印您连接到的网络的SSID:
序列号。打印(“SSID:”);
Serial.println(WiFi.SSID());
//打印您的WiFi屏蔽的IP地址:
ip地址ip=WiFi.localIP();
串行打印(“IP地址:”);
序列号println(ip);
//打印接收到的信号强度:
长rssi=WiFi.rssi();
串行打印(“信号强度(RSSI):”;
串行打印(rssi);
Serial.println(“dBm”);
}

您是否收到任何错误?我看不到错误您是否查看了防火墙以防出现…无错误,但我没有收到unityif(udpClient1.Available>0)-udpClient.Available始终导致0。。。。我在防火墙中创建了一个规则,允许该端口上的所有内容。但这并不是问题所在,因为在Udp终端中,我从arduino接收到消息。
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

//SSID of your network
char ssid[] = "TUI"; //SSID of your Wi-Fi router
char pass[] = "password"; //Password of your Wi-Fi router
int keyIndex = 0;

unsigned int localPort = 4000; 
char packetBuffer[255]; //buffer to hold incoming packet
char  ReplyBuffer[] = "";       // a string to send back

WiFiUDP Udp;

//input
const int buttonPin = 4;
const int ledpin = D1;
int buttonState = LOW;


void setup()
{
  pinMode(buttonPin, INPUT);
  pinMode(ledpin, OUTPUT);
  IPAddress ip(192, 175, 0, 20); 
  IPAddress gateway(192, 175, 0, 1); 
  IPAddress subnet(255, 255, 255, 0); 
  IPAddress DNS(192, 175, 0, 1); 
  Serial.begin(115200);
  WiFi.config(ip, gateway, subnet, DNS);  
  delay(100); 
  //WiFi.mode(WIFI_STA); 
  WiFi.begin(ssid, pass); 
  Serial.print("Connecting"); 
  while (WiFi.status() != WL_CONNECTED) { 
    Serial.print("."); 
    delay(200);  
  }   
  while (WiFi.waitForConnectResult() != WL_CONNECTED) { 
    Serial.println(); 
    Serial.println("Fail connecting"); 
    delay(5000); 
    ESP.restart(); 
  }   
  Serial.print("   OK  "); 
  Serial.print("Module IP: "); 
  Serial.println(WiFi.localIP());
  printWifiStatus(); 
  // if you get a connection, report back via serial:
  Udp.begin(localPort);
} 

void loop () {// if there's data available, read a packet
  int packetSize = Udp.parsePacket();

  if (packetSize) {
    Serial.print("Received packet of size ");
    Serial.println(packetSize);
    Serial.print("From ");
    IPAddress remoteIp = Udp.remoteIP();
    Serial.print(remoteIp);
    Serial.print(", port ");
    Serial.println(Udp.remotePort());

    // read the packet into packetBufffer
    int len = Udp.read(packetBuffer, 255);
    if (len > 0) {
      packetBuffer[len] = 0;
    }
    Serial.println("Contents:");
    Serial.println(packetBuffer);

    String str(packetBuffer);

    if(str == "hello from unity"){
      digitalWrite(ledpin, HIGH); 
    }


     buttonState = digitalRead(buttonPin);
     if(buttonState == HIGH){
      String str1 = "Button1 pressed"; 
      str1.toCharArray(ReplyBuffer, 50); 
     }
     else{
      String str1 = "Button1 off"; 
      str1.toCharArray(ReplyBuffer, 50);
     }

     Serial.println(ReplyBuffer);
      Serial.println(Udp.remoteIP());
      Serial.println(Udp.remotePort());


    // send a reply, to the IP address and port that sent the packet
    Udp.beginPacket(Udp.remoteIP(), 4001);
    Udp.write(ReplyBuffer);
    Udp.endPacket();
  }

  else{
      digitalWrite(ledpin, LOW);   
    }
    delay(10);
  }

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}