简体   繁体   English

如果Tcplistener不可用,则Tcpclient连接冻结

[英]Tcpclient connection freeze if Tcplistener is not available

I have tried 我努力了

    Connectionclient.ReceiveTimeout = 10000;
    Connectionclient.Connect("127.0.0.1", 10072);

if TcpListener is running, it works fine. 如果TcpListener正在运行,则可以正常工作。 but if the TcpListener is not running, my tcpclient will freeze itself like 1 sec before catch the exception. 但是如果TcpListener没有运行,我的tcpclient将在捕获异常之前像1秒钟一样冻结自身。 meanwhile, my connecting message is also being freeze. 同时,我的连接消息也被冻结。

I'm just trying to make a Login screen like all online games have. 我只是想像所有在线游戏一样制作一个登录屏幕。

So, how can I solve this problem, or what should I go read to find the solution my self. 因此,我该如何解决该问题,或者我应该阅读些什么以找到自己的解决方案。

The TcpClient.Connect method is synchronous and as such will block the calling thread until the connect operation has completed either successfully or with an error. TcpClient.Connect方法是同步的 ,因此将阻塞调用线程,直到连接操作成功完成或出现错误为止。

If the calling thread happens to be the thread that owns the window handle then the window will appear unresponsive. 如果调用线程恰好是拥有窗口句柄的线程,则窗口将显示为无响应。

In order to solve your problem you could use the asynchronous counterpart to the synchronous connect method that will carry out the connect operation on a separate worker thread. 为了解决您的问题,您可以使用与异步连接方法相对应的异步方法,该方法将在单独的工作线程上执行连接操作。

labelConnectionState.Text = "Connecting";
Connectionclient.BeginConnect("..", 43594, ConnectCallback,  Connectionclient);
...
private static void ConnectCallback(IAsyncResult asyncResult)
{
    try
    {
        TcpClient Connectionclient = (TcpClient) asyncResult.AsyncState;
        Connectionclient.EndConnect(asyncResult);
        labelConnectionState.Text = "Connected";
    }
    catch (SocketException socketException)
    {
        labelConnectionState.Text = "Server unavailable";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM