我有一个通过以太网电缆直接连接到运行Unity3d的Win10笔记本电脑的PLC。我的目标是使用UDP连接将数据从PLC发送到Unity模型。
当前,PLC每秒钟发送一次消息,它们在Wireshark中可见。
Unity一半运行着一个Receive-Thread。它可以通过本地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")
可用于解决问题的工具:
netstat -aon
检查套接字是否正在运行。 感谢Trevor和Programmer的帮助。
关于c# - 在Unity3D中无法接收来自PLC的C#UDP消息,但在Wireshark中可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50470502/