【发布时间】:2021-05-05 14:45:44
【问题描述】:
我在与 UDP 设备通信时遇到问题
public IPEndPoint sendEndPoint;
public void senderUdpClient(byte message_Type, byte Command_Class, byte command_code,int argument1, int argument2)
{
string serverIP = "192.168.2.11";
int sendPort = 40960;
int receivePort = 40963;
// Calcul CheckSum
// We know the message plus the checksum has length 12
var packedMessage2 = new byte[12];
var packedMessage_hex = new byte[12];
// We use the new Span feature
var span = new Span<byte>(packedMessage2);
// We can directly set the single bytes
span[0] = message_Type;
span[1] = Command_Class;
span[2] = command_code;
// The pack is <, so little endian. Note the use of Slice: first the position (3 or 7), then the length of the data (4 for int)
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(3, 4), argument1);
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(7, 4), argument2);
// The checksum
// The sum is modulo 255, because it is a single byte.
// the unchecked is normally useless because it is standard in C#, but we write it to make it clear
var sum = unchecked((byte)packedMessage2.Take(11).Sum(x => x));
// We set the sum
span[11] = sum;
// Without checksum
Console.WriteLine(string.Concat(packedMessage2.Take(11).Select(x => $@"\x{x:x2}")));
// With checksum
Console.WriteLine(string.Concat(packedMessage2.Select(x => $@"\x{x:x2}")));
Console.WriteLine(string.Concat(packedMessage2.Take(1).Select(x => $@"\x{x:x2}")));
UdpClient senderClient = new UdpClient();
sendEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), sendPort);
try
{
senderClient.Connect(this.sendEndPoint);
senderClient.Send(packedMessage2, packedMessage2.Length);
//IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), receivePort);
Thread.Sleep(5000);
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = senderClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
senderClient.Close();
MessageBox.Show("Message Sent");
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
表格1
ObjHundler.senderUdpClient(1, 1, 0x24, 0 , 0);
我在那里构建我的消息并通过端口 40960 发送它
我通过端口 40963 得到响应
在wireshark上,我发送消息,设备发送响应,但代码在这一行崩溃 Byte[] receiveBytes = senderClient.Receive(ref RemoteIpEndPoint);
不填表也不显示任何错误信息 我的代码中是否缺少某些内容? 可能是什么问题
Netstat -a cmd pour l'ip que j'utilise pour l'envoie 192.168.2.20 [CMD Netstat -a]
【问题讨论】:
-
尝试:new IPEndPoint(IPAddress.Any, receivePort);您的接收端点可能无效。
-
我已经尝试过了,但没有解决问题
-
您是否获得了有效的端点?
-
是 => {192.168.2.11:40961}
-
我会移除睡眠并使用 IP.Any。然后检查嗅探器以查看是否正在发生 [FIN}。您是否在接收数据的同一台机器上使用嗅探器?可能不允许接收数据的接口的检查掩码:来自 cmd.exe >IPConfig/all