Observable.FromAsyncPattern 与 UDPClient.EndReceive 和 ref 远程端点参数
我正在学习反应式扩展并尝试重构我的一些代码。
UDPClient.EndReceive
采用 ref IPEndPoint
参数,因此我目前可以使用此功能:
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, 1234));
IPEndPoint ep = null;
var async = Observable.FromAsyncPattern<byte[]>(receiverUDP.BeginReceive, (i) => receiverUDP.EndReceive(i, ref ep));
var subscr = async().Subscribe(x => Console.WriteLine(ASCIIEncoding.ASCII.GetString(x)));
如果我的订阅者需要访问远程 IPEndPoint,该怎么办?在我当前的化身中,我正在使用事件,并传回包装 byte[]
和 IPEndPoint
的自定义类。我无论如何也无法弄清楚如何使用 Rx 来做到这一点。
I'm learning about Reactive extensions and trying to re-factor some of my code.
UDPClient.EndReceive
takes a ref IPEndPoint
parameter, so I currently have this working:
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, 1234));
IPEndPoint ep = null;
var async = Observable.FromAsyncPattern<byte[]>(receiverUDP.BeginReceive, (i) => receiverUDP.EndReceive(i, ref ep));
var subscr = async().Subscribe(x => Console.WriteLine(ASCIIEncoding.ASCII.GetString(x)));
What if my subscribers need access to the remote IPEndPoint? In my current incarnation I'm using events, and passing back a custom class which wraps byte[]
and IPEndPoint
. I cannot for the life of me, work out how to do this with Rx.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您已经为
byte[]
和IPEndPoint
创建了包装类,为什么不使用Select
将其作为序列返回:If you've already created a wrapper class for
byte[]
andIPEndPoint
why not return that as the sequence usingSelect
:对于其他人来说,有一种稍微简单、更现代的方法可以使用
ReceiveAsync
来执行此操作:您可以使用 IPAddress.Any: 调用它,
然后使用
Select
来投影流式传输到您想要的任何类型。For anyone else looking, there's a slightly simpler, and more modern way to do this using
ReceiveAsync
:You can call it with IPAddress.Any:
and then use
Select
to project the stream to whatever type you want.