小编Cyr*_*iac的帖子

来自Socket的UWP SendToAsync导致AddressFamilyNotSupported

我正在使用UWP 的Socket类通过UDP将数据发送到特定设备.

问题是,经过几次发送和返回后,我的SocketAsyncEventArgs发送被卡住了,在SocketError中我得到了AddressFamilyNotSupported.

类的初始化就是这样完成的

m_Socket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
m_Socket.Bind(new IPEndPoint(IPAddress.Any, 51020));
m_SocketReceiveEventArgs = new SocketAsyncEventArgs();
m_SocketReceiveEventArgs.Completed += SocketArgsReceived;
m_SocketReceiveEventArgs.SetBuffer(m_ReceivingBuffer, 0,m_ReceivingBuffer.Length);
m_SocketSendEventArgs = new SocketAsyncEventArgs();
m_SocketSendEventArgs.Completed += SocketArgsSend;
Run Code Online (Sandbox Code Playgroud)

当我发送via时(循环的条件仅用于测试目的):

m_SocketSendEventArgs.SetBuffer(aunReqBuffer, 0,aunReqBuffer.Length);
m_Socket.SendToAsync(m_SocketSendEventArgs);

while (m_SocketSendEventArgs.BytesTransferred == 0)
{
    // AddressFamilyNotSupported happens here after a few packets have been send
}
Run Code Online (Sandbox Code Playgroud)

并通过访问套接字并调用ReceiveFromAsync()来在一个单独的线程中重复接收,这是有效的.

知道它突然停止工作的原因吗?如果您需要更多信息,我很乐意帮忙.

更新08.03.2017

我将发送方法包装在using语句中,现在它可以工作了.有人能向我解释这个吗?特别是我得到的奇怪的SocketError.在我的记忆中,我已经尝试过.Dispose()手动,所以我混淆了那里有什么不同.

using (var sendargs = new SocketAsyncEventArgs())
{
    sendargs.Completed += SocketArgsSend;
    sendargs.RemoteEndPoint = m_remoteIpEndPoint;
    sendargs.SetBuffer(aunReqBuffer, 0, aunReqBuffer.Length);
    m_Socket.SendToAsync(sendargs);
    while (sendargs.BytesTransferred == 0)
    {
        // …
Run Code Online (Sandbox Code Playgroud)

c# sockets asynchronous udp uwp

10
推荐指数
1
解决办法
399
查看次数

标签 统计

asynchronous ×1

c# ×1

sockets ×1

udp ×1

uwp ×1