来自PLC的C# UDP消息无法在Unity3D中接收,但在Wireshark中可见



我有一个PLC,通过以太网电缆直接连接到运行Unity3d的Win10笔记本电脑。我的目标是使用 UDP 连接将数据从 PLC 发送到 Unity 模型。

目前,PLC每秒发送一次消息,它们在Wireshark中可见。

Unity 部分有一个正在运行的接收线程。它能够通过本地 127.0.0.1 IP 连接接收。我还在 Unity 中实现了一个发送器来测试它,它按预期工作。

不起作用的是接收来自 PLC 的消息,定向到与内部连接相同的端口。

到目前为止,我...

  • 。将以太网端口设置为静态 IP (192.168.0.41(
  • 。在防火墙中打开UDP通信的端口,这应该不是问题。
  • 。更改了接收端口(当前设置为 8052(
  • 。尝试了客户端设置的变化,没有任何变化。
  • 。通过各种线程和评论部分进行研究和挖掘,但没有成功。虽然我发现其他人遇到了同样的问题,但没有人发布答案。

Unity3d C# 接收代码(缩短为相关部分(:

private void init()
{
port = 8052;
receiveThread = new Thread( new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
}
private void ReceiveData()
{
// create a client
client = new UdpClient(port);
while (true)
{
// if an Error occours the program doesn't crash
try
{
// Create connection point and receiving client + receiving bytes
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, port);
byte[] data = client.Receive(ref anyIP);
print("Number of bytes: " + data.Length.ToString());
/*
* use the received data
*/
}
catch (Exception err)
{
//Output if receiving experienced an error
print(err.ToString());
}
}
}
}

我认为可能是问题所在:

  • 还有另一层可以阻止防火墙旁边的连接,我还没有考虑过
  • 客户端设置需要不同才能从外部源接收消息。
  • 需要一个 asychron UDP 客户端

(接收(代码基于: 简单的 UDP 实现。

另外一个问题,因为我对网络很陌生:如果Wireshark可以看到软件包,它不应该已经通过了防火墙和其他可能的阻塞层吗?还是Wireshark正在寻找更低的通信层?

提前谢谢你!

来自Wireshark的截图: 多条传入消息 一条消息的详细信息

因此,经过一段非常令人沮丧的旅程,我发现了一个不太好但可以完成工作的解决方法:

我编写了一个 python 脚本,用于打开套接字,接收外部数据并通过本地 IP 将其转发到 Unity。这行得通。

这是代码:

# Import libraies
import socket
import time
# Set send IP adress and port
UDP_IP = "127.0.0.1"
UDP_PORT_Rec = 8052
UDP_PORT_Unity = 8055
print("Receiving on Port:" + str(UDP_PORT_Rec))
print("Sending to IP:" + UDP_IP + ":" + str(UDP_PORT_Unity))
# Set socket to send udp messages and bind port
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind(('',UDP_PORT_Rec));
## Keep sending message from file location
while True:
data, addr = sock.recvfrom(1024) #buffer size, hopefully no problem if too big
print("Received")
sock.sendto(data, (UDP_IP, UDP_PORT_Unity))
print("Send")

对故障排除有用的工具:

  • 安装Wireshark!它可能是跟踪互联网流量的最佳工具。在 Wireshark 中可见的软件包对于普通应用程序可能不可见!
  • 使用数据包发送器生成和接收流量。应用程序使用基本方法来接收包 - 如果可以,那么您的程序也应该能够。
  • 请与netstat -aon核实您的套接字是否正在运行。
  • 完成:检查您的防火墙设置。

感谢特雷弗和程序员的帮助。

相关内容

最新更新