0

我正在尝试通过 TCP/IP 从 WP8 连接到 IP/端口。我使用 socket.ConnectAsync() 来启动连接并像这样指定一个 Completed Event

        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);
4

1 回答 1

0

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

于 2014-05-24T20:51:16.017 回答