async TcpClient.Connect()如何使用它?

时间:2014-01-15 11:48:01

标签: c# asynchronous tcp tcpclient

目前我正在同步将我的客户端连接到服务器 但是,服务器有时不可用,所以我认为使用async会更好,所以我已经可以收集并格式化我想要稍后发送的数据。我发现我正在寻找的方法可能是TcpClient.BeginConnect 不幸的是,我对异步操作完全不熟悉,所以参数很奇怪 一个问题:我是否有必要单独使用IP和端口,即不使用IPEndPoint? 但更重要的问题是:AsyncCallback和Object,这些是什么? 我是否需要更改服务器上的任何内容?
我想我明白snyc或asnyc是本地选择而不影响另一方,至少不兼容。
最后:Here我读到关键字asnyc并等待:在哪里使用它们以及如何使用它们?

这里有一些伪代码来展示我拥有的和我想要的东西

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

1 个答案:

答案 0 :(得分:1)

您需要创建一个新的AsyncCallback并将其设置为一个特定的空白,一旦TcpClient完成连接到主机,就会完成某些操作。您可能还想通过检查TcpClient

的值来检查TcpClient.Connected连接是否成功

示例

以下示例说明了在端口80上与google.com的异步TcpClient连接

static TcpClient cli = new TcpClient(); //Initialize a new TcpClient
static void Main(string[] args)
{
    send("Something");
    Console.ReadLine();
}
private static void doSomething(IAsyncResult result)
{
    if (cli.Connected) //Connected to host, do something
    {
        Console.WriteLine("Connected"); //Write 'Connected'
    }
    else
    {
        //Not connected, do something
    }
    Console.ReadLine(); //Wait for user input
}
private static void send(string msg)
{
    AsyncCallback callBack = new AsyncCallback(doSomething); //Set the callback to the doSomething void
    cli.BeginConnect("google.com", 80, callBack, cli); //Try to connect to Google on port 80
}

这是一种更好的方式来完成你在评论中所描述的内容

System.Threading.Thread newThread = new System.Threading.Thread((System.Threading.ThreadStart)delegate {
//Do whatever you want in a new thread
    while (!cli.Connected)
    {
        //Do something
    }
});
newThread.Start(); //Start executing the code inside the thread
//This code will still run while the newThread is running
Console.ReadLine(); //Wait for user input
newThread.Abort(); //Stop the thread when the user inserts any thing