Question

I have tried

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

if TcpListener is running, it works fine. but if the TcpListener is not running, my tcpclient will freeze itself like 1 sec before catch the exception. 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.

Was it helpful?

Solution

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.

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";
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top