Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to (really) cancel a ConnectAsync request on Windows Phone?

I'm developing a Windows Phone application that will connect to my server. It does this by using ConnectAsync when you push the login button. But if the server is down and you want to cancel the connecting attempt, what to do?

Here is is the current client code complete with my latest try at shutting the socket connection down. It is to be assumed that you can easily implement a timeout once you know how to turn the connection off.

    private IPAddress ServerAddress = new IPAddress(0xff00ff00); //Censored my IP
    private int ServerPort = 13000;
    private Socket CurrentSocket;
    private SocketAsyncEventArgs CurrentSocketEventArgs;
    private bool Connecting = false;

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            if (Connecting)
            {
                CurrentSocket.Close();
                CurrentSocket.Dispose();
                CurrentSocketEventArgs.Dispose();
                CurrentSocket = null;
                CurrentSocketEventArgs = null;
            }
            UserData userdata = new UserData();
            userdata.Username = usernameBox.Text;
            userdata.Password = passwordBox.Password;

            Connecting = ConnectToServer(userdata);
        }
        catch (Exception exception)
        {
            Dispatcher.BeginInvoke(() => MessageBox.Show("Error: " + exception.Message));
        }
    }

    private bool ConnectToServer(UserData userdata)
    {
        CurrentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        //Create a new SocketAsyncEventArgs
        CurrentSocketEventArgs = new SocketAsyncEventArgs();
        CurrentSocketEventArgs.RemoteEndPoint = new IPEndPoint(ServerAddress, ServerPort);
        CurrentSocketEventArgs.Completed += ConnectionCompleted;
        CurrentSocketEventArgs.UserToken = userdata;
        CurrentSocketEventArgs.SetBuffer(new byte[1024], 0, 1024);

        CurrentSocket.ConnectAsync(CurrentSocketEventArgs);
        return true;
    }

Edit: A thought that struck me is that perhaps it's the server computer that stacks up on requests even though the server software isn't on? Is that possible?

like image 999
Switchice Avatar asked Oct 22 '22 17:10

Switchice


1 Answers

I believe

socket.Close()

should cancel the async connection attempt. There may be some exceptions that need to be caught as a consequence.

like image 140
MarcF Avatar answered Nov 01 '22 14:11

MarcF