我正在尝试通过以太网(从控制器)接收UDP数据,并且遇到了一些麻烦。我知道控制器正在发送数据,因为我可以看到它通过Wireshark传递,但是我尝试过的所有方法都没有用。下面的代码是我发现的最能接收我想要的数据的代码。有关更多信息:控制器IP和端口为192.168.82.27:1743,我端的接收IP和端口为192.168.82.21:1740
public class UDPListener
{
static UdpClient client = new UdpClient(1740);
public static void Main()
{
try
{
client.BeginReceive(new AsyncCallback(recv), null);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
while (true)
{
}
}
//CallBack
private static void recv(IAsyncResult res)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 1743);
byte[] received = client.EndReceive(res, ref RemoteIpEndPoint);
//Process code
Console.WriteLine(RemoteIpEndPoint + " : " + Encoding.ASCII.GetString(received));
client.BeginReceive(new AsyncCallback(recv), null);
}
}
此代码应该起作用:
public class Receiver
{
private readonly UdpClient udp;
private IPEndPoint ip = new IPEndPoint(IPAddress.Any, 1740);
public Receiver()
{
udp = new UdpClient
{
ExclusiveAddressUse = false
};
udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udp.Client.Bind(ip);
}
public void StartListening()
{
udp.BeginReceive(Receive, new object());
}
private void Receive(IAsyncResult ar)
{
var bytes = udp.EndReceive(ar, ref ip);
StartListening();
}
}