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

C# UDP messages from PLC can not be received in Unity3D, but is visible in Wireshark

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

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

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

什么不起作用,是从 PLC 接收消息,指向与内部连接相同的端口。

到目前为止我...

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());
            }
        }
    }
}

我认为可能是问题所在:

(接收)代码基于: Simple UDP implementation.

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

提前致谢!

Wireshark 的屏幕截图: Multiple incoming messages Details of one message

所以在经历了一段非常令人沮丧的旅程之后,我找到了一个虽然不太好但可以解决问题的解决方法:

我写了一个 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!它可能是跟踪 Internet 流量的最佳工具。在 Wireshark 中可见的包对于普通应用程序可能不可见!
  • 使用Packet Sender生成和接收流量。该应用程序使用基本方法来接收包 - 如果可以,那么您的程序也应该可以。
  • 检查 netstat -aon 是否您的插座是 运行。
  • 完成:检查您的防火墙设置。

感谢 Trevor 和程序员的帮助。