【发布时间】:2018-11-28 20:58:01
【问题描述】:
我有简单的 MCU 网络,仅支持 ARP、广播和单播 UDP/IP 协议,我直接连接到 MCU,无需 PC 网络(点对点)。
在 C# 中,我有两个 UDP 套接字 - 发送者和侦听器。监听器绑定到端点(监听端口 60001)。
但我的程序只有在运行 Wireshark 时才能运行。如果没有 Wireshark,它只能发送广播数据包,但不能接收。
MCU实现ARP协议(我也在Windows中尝试了静态IP。命令arp -s)。我尝试关闭 Windows 10 防火墙和防病毒软件,以管理员身份运行程序,但什么也没有。只有当我运行 Wireshark 时,我的 C# 程序才会接收数据包。
IP 标头校验和正确 - 我在 Wireshark 中启用了检查。 udp checksum = 0(PC也不计算checksum)
C#代码:
public void UdpConnect() {
udpSender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpListener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpListener.Bind(new IPEndPoint(IPAddress.Any, 60001));
// MCU send data to dstIP = PC_IP and dstPort = 60001
}
int Send() {
byte[] dgram = tx_buf.ToArray();
int n = udpSender.SendTo(dgram, SocketFlags.DontRoute, new IPEndPoint(IPAddress.Parse("192.168.0.200"), 60000));
// PC send data to MCU IP 192.168.0.200 and dstPort = 60000
Debug.WriteLine("Send " + n + " bytes");
return n;
}
byte[] Receive(int timeout_ms = 3000) {
byte[] data = new byte[1518];
int byteCount = 0;
Stopwatch sw = new Stopwatch();
sw.Start();
do {
if (udpListener.Available != 0) {
Debug.WriteLine("Available: " + udpListener.Available);
byteCount = udpListener.Receive(data, data.Length, SocketFlags.None);
Debug.WriteLine("Received UDP packet length: " + byteCount);
}
else
Thread.Sleep(100);
} while (byteCount == 0 && sw.ElapsedMilliseconds < timeout_ms);
return byteCount == 0 ? null : data.Take(byteCount).ToArray();
}
byte[] SendReceive(int timeout_ms = 3000, int attempts = 3) {
byte[] result = null;
for (int i = 0; i < attempts; i++) {
Send();
result = Receive(timeout_ms);
if (result != null)
break;
else
Debug.WriteLine("Attempt " + (i + 1) + " failed");
}
if (result == null) {
Debug.WriteLine("UDP receiver timeout");
throw new TimeoutException();
}
return result;
}
【问题讨论】:
-
您好,请出示相关代码。
-
这似乎更像是一个网络问题而不是编程问题。
-
您的问题与 C#、网络、操作系统/防火墙有关吗?尝试缩小范围。也许从使用 sourceforge.net/projects/sockettest 之类的东西开始,而不是你的 C# 应用程序,看看它是否表现出相同的行为。也许在同一个盒子上运行客户端和服务器以消除操作系统防火墙等。
-
这个程序和我的一样。如果我运行 Wireshark - 程序会捕获数据包,如果我停止 Wireshark - 程序不会捕获数据包。 (我每秒从 MCU 发送 UDP 数据包)
-
也许我需要做 SocketPermission?
标签: c# sockets udp ethernet xmos