设备与电脑使用网线直连,设备通过广播模式向固定端口发送数据。现在需要我这边使用进行数据接收。但我使用C# 的udpClient一直收不到数据。
但网络调试助手是可以收到的,因此排除了电脑原因。
下面是我的代码:我尝试了使用线程方式与异步方式都无法接收到数据。
求帮助啊
public AsyncUDP(IPAddress localIPAddress, int listenPort, int maxClient)
{
this.Address = localIPAddress;
this.Port = listenPort;
this.Encoding = Encoding.Default;
_maxClient = maxClient;
//_clients = new List<AsyncUDPSocketState>();
_server = new UdpClient(new IPEndPoint( Address,Port));
_server.EnableBroadcast = true;
//Task.Factory.StartNew(() => { Receive(); });
_server.BeginReceive(ReceiveDataAsync, null);
}
//使用线程方式接收
private void Receive()
{
while (IsRunning)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any,0);
var bytes = _server.Receive(ref ip);
Console.WriteLine("接收:"+bytes.Length);
}
}
//使用异步方式接收
private void ReceiveDataAsync(IAsyncResult ar)
{
IPEndPoint remote = null;
byte[] buffer = null;
try
{
buffer = _server.EndReceive(ar, ref remote);
AsyncUDPState state = new AsyncUDPState();
state.buffer = buffer;
state.remote = remote;
//触发数据收到事件
RaiseDataReceived(state);
}
catch (Exception)
{
//TODO 处理异常
RaiseOtherException(null);
}
finally
{
if (IsRunning && _server != null)
_server.BeginReceive(ReceiveDataAsync, null);
}
}