我正在尝试通过 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);