gpt4 book ai didi

c# - 如何(真正)取消 Windows Phone 上的 ConnectAsync 请求?

转载 作者:太空狗 更新时间:2023-10-29 23:32:39 25 4
gpt4 key购买 nike

我正在开发一个将连接到我的服务器的 Windows Phone 应用程序。它通过在您按下登录按钮时使用 ConnectAsync 来实现。但是如果服务器宕机了,你想取消连接尝试,怎么办?

这是我最近尝试关闭套接字连接时完成的当前客户端代码。假设您知道如何关闭连接后就可以轻松实现超时。

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

编辑:让我印象深刻的一个想法是,即使服务器软件没有打开,也许是服务器计算机在请求时堆积起来?那可能吗?

最佳答案

我相信

socket.Close()

应该取消异步连接尝试。因此可能需要捕获一些异常。

关于c# - 如何(真正)取消 Windows Phone 上的 ConnectAsync 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14902813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com