未连接时触发 C# BeginConnect 回调 [英] C# BeginConnect callback is fired when not connected
问题描述
使用 tcpClient.BeginConnect
会触发异步回调,即使客户端没有任何连接.然后我得到一个关于尝试 .GetStream()
的异常.
Using tcpClient.BeginConnect
fires the async callback even though there is nothing for the client to connect to. I then get an exception about trying to .GetStream()
.
public void SetupSocket() {
try {
tcpClient = new TcpClient();
tcpClient.BeginConnect(host, port, ConnectCallback, tcpClient);
Console.WriteLine("begin connect");
}
catch (Exception e) {
return;
}
}
private void ConnectCallback(IAsyncResult result) {
if (OnClientEvent != null)
OnClientEvent(this, new ClientEventArgs(Action.Connect));
Console.WriteLine("get stream");
stream = tcpClient.GetStream();
Console.WriteLine("got stream");
BeginReadAsync();
}
输出 get stream
然后在连接之前尝试在 tcpClient 上使用 GetStream 的异常.
Output get stream
and then exception about trying to use GetStream on tcpClient before it is connected.
推荐答案
传递给 BeginConnect
的回调在连接操作完成时被调用,无论连接到端点是成功还是失败.
The callback passed to BeginConnect
is called when the connect operation completes, regardless of whether it succeeds in connecting to the endpoint or fails.
在BeginConnect
回调中,您需要使用您收到的IAsyncResult
对象调用EndConnect
,以完成连接操作.在调用 EndConnect
之前,套接字不可用;之后,如果socket连接成功,就可以继续读写了.
In the BeginConnect
callback, you need to call EndConnect
with the IAsyncResult
object you received, in order to complete the connect operation. The socket isn't usable until EndConnect
is called; after that, if the socket successfully connected, you can proceed with reading and writing.
这篇关于未连接时触发 C# BeginConnect 回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!