【发布时间】:2014-02-03 20:57:43
【问题描述】:
目前我正在将我的客户端同步连接到服务器。
但是,服务器有时不可用,所以我认为使用异步会更好,这样我就可以收集并格式化稍后要发送的数据。我发现我要找的方法大概是TcpClient.BeginConnect
不幸的是,我对异步操作完全陌生,所以参数让我很奇怪。
一方面:是否有特定原因我必须单独使用 IP 和端口,即不使用 IPEndPoint?
然而更重要的问题:AsyncCallback 和 Object,它们是什么?
我需要更改服务器上的任何内容吗?
我想我明白 snyc 或 asnyc 是本地选择,不会影响对方,至少不会影响兼容性。
最后:Here 我读到了关键字 asnyc 和 await:在哪里使用它们以及如何使用它们?
这里有一个小伪代码来演示我拥有什么以及我想要什么
private static void send(string msg) {
TcpClient cli = new TcpClient(localEP);
bool loop = true;
while(loop) { //trying over and over till it works
try { //is bad practice and inefficient
cli.Connect(remoteEP);
} catch (Exception) {
;
}
if(cli.Connected)
break;
}
var blah = doOtherThings(msg);
useTheClient(blah);
}
现在我希望它如何工作
private static void send(string msg) {
TcpClient cli = new TcpClient(localEP);
cli.BeginConnect(remoteEP); //thread doesn't block here anymore + no exceptions
var blah = doOtherThings(msg); //this now gets done while cli is connecting
await(cli.connect == done) //point to wait for connection to be established
useTheClient(blah);
}
【问题讨论】:
标签: c# asynchronous tcp tcpclient