WP8套接字ConnectAsync:已完成的处理程序始终返回成功?

时间:2013-06-03 11:36:49

标签: c# sockets windows-phone-8 connect

我正在尝试通过TCP / IP从WP8连接到ip / port。我使用socket.ConnectAsync()来启动Connection并指定像这样的完成事件

        socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
        {
            lasterrorstring = e.SocketError.ToString();
            if (e.SocketError != SocketError.Success)
            {
                 :
            }
        });

一切正常。所以我可以正确地与其他主机交谈。但是,错误的情况让我很烦恼。出于某种原因,e.SocketError始终返回Success。我甚至尝试连接到不存在的ip。它也报告了成功。甚至Send()之后也会报告成功。这有什么不对?

为了完整性,这是我的整个连接设置代码

        Socket _socket = null;

        DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);

        // Create a stream-based, TCP socket using the InterNetwork Address Family. 
        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        // Create a SocketAsyncEventArgs object to be used in the connection request
        SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
        socketEventArg.RemoteEndPoint = hostEntry;

        // Inline event handler for the Completed event.
        // Note: This event handler was implemented inline in order to make this method self-contained.
        socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
        {
            // Retrieve the result of this request
            lasterrorstring = e.SocketError.ToString();
            if (e.SocketError != SocketError.Success)
            {
                res = 1;
            }
        });

        // Make an asynchronous Connect request over the socket
        _socket.ConnectAsync(socketEventArg);

1 个答案:

答案 0 :(得分:0)

这是一个老问题,但无论如何。它也发生在我身上,看起来直到你通过SendAsync方法发送东西,它认为它是连接的。但是在SendAsync的完成事件中,e.SocketError不会返回成功。因此,您可以在ConnectAsync返回成功后立即发送空数据,以了解它是否真的已连接。