C#框架中的UDP数据报套接字(来自UWP的端口)
我正在尝试将以下代码从UWP移植到C#框架(WPF应用程序)C#框架中的UDP数据报套接字(来自UWP的端口),c#,.net,datagram,C#,.net,Datagram,我正在尝试将以下代码从UWP移植到C#框架(WPF应用程序) 有什么建议吗?谢谢找到原因,是windows防火墙阻止了访问 public class DatagramSocket : IDatagramSocket { private Windows.Networking.Sockets.DatagramSocket socket; public DatagramSocket() { socket = new Windows.Networking.Soc
有什么建议吗?谢谢找到原因,是windows防火墙阻止了访问
public class DatagramSocket : IDatagramSocket
{
private Windows.Networking.Sockets.DatagramSocket socket;
public DatagramSocket()
{
socket = new Windows.Networking.Sockets.DatagramSocket();
socket.MessageReceived += Socket_MessageReceived;
}
public event Action<DatagramSocketMessage> MessageReceived;
public async Task Bind(string profile, int liveViewPort)
{
Debug.WriteLine($"Binding to {profile} on port {liveViewPort}");
await socket.BindEndpointAsync(new HostName(profile), liveViewPort.ToString());
}
public void Dispose()
{
socket.Dispose();
}
private void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
{
using (var reader = args.GetDataReader())
{
var buf = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(buf);
MessageReceived?.Invoke(new DatagramSocketMessage(args.RemoteAddress.CanonicalName, buf));
}
}
}
public class DatagramSocket : IDatagramSocket
{
public UdpClient socket;
public IPEndPoint ep;
public event Action<DatagramSocketMessage> MessageReceived;
public async Task Bind(string profile, int liveViewPort)
{
socket = new UdpClient(profile, liveViewPort);
socket.BeginReceive(OnUdpData, socket);
}
void OnUdpData(IAsyncResult result)
{
if (_isDisposed)
return;
var socket = result.AsyncState as UdpClient;
// points towards whoever had sent the message:
IPEndPoint source = new IPEndPoint(0, 0);
// get the actual message and fill out the source:
byte[] message = socket.EndReceive(result, ref source);
MessageReceived?.Invoke(new DatagramSocketMessage(socket.ToString(), message));
socket.BeginReceive(OnUdpData, socket);
}
private volatile bool _isDisposed;
public void Dispose()
{
_isDisposed = true;
socket.Dispose();
}
}
public async Task Bind(string profile, int liveViewPort)
{
Task.Run(async () =>
{
using (var udpClient = new UdpClient(profile, liveViewPort))
{
while (!_isDisposed)
{
var receivedResults = await udpClient.ReceiveAsync();
MessageReceived?.Invoke(new DatagramSocketMessage(udpClient.ToString(), receivedResults.Buffer));
}
}
});
}