以下代码是否正确,我正在为UdpClient
进行一些设置,然后使用Observable.Using(()
?
请建议是否有其他方法可以写出来?
public static IObservable<UdpReceiveResult> UdpStream()
{
return Observable.Defer(() =>
{
UdpClient receiverUDP = new UdpClient();
receiverUDP.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
receiverUDP.EnableBroadcast = true;
receiverUDP.Client.ExclusiveAddressUse = false;
receiverUDP.Client.Bind(new IPEndPoint(IPAddress.Any, 514));
return Observable.Using(() => receiverUDP,
udpClient => Observable.Defer(() =>
udpClient.ReceiveAsync().ToObservable()).Repeat());
});
}
答案 0 :(得分:1)
根据评论中的要求:
public static IObservable<UdpReceiveResult> UdpStream()
{
return Observable.Defer(() =>
{
UdpClient receiverUDP = new UdpClient();
receiverUDP.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
receiverUDP.EnableBroadcast = true;
receiverUDP.Client.ExclusiveAddressUse = false;
receiverUDP.Client.Bind(new IPEndPoint(IPAddress.Any, 514));
return
Observable
.Using(
() => receiverUDP,
udpClient =>
Observable
.Defer(() =>
Observable
.FromAsync(() => udpClient.ReceiveAsync()))
.Repeat());
});
}
就个人而言,我这样做:
public static IObservable<UdpReceiveResult> UdpStream()
{
return
Observable
.Using(
() =>
{
UdpClient receiverUDP = new UdpClient();
receiverUDP.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
receiverUDP.EnableBroadcast = true;
receiverUDP.Client.ExclusiveAddressUse = false;
receiverUDP.Client.Bind(new IPEndPoint(IPAddress.Any, 514));
return receiverUDP;
},
udpClient =>
Observable
.Defer(() =>
Observable
.FromAsync(() => udpClient.ReceiveAsync()))
.Repeat());
}