重新连接到服务器 [英] Reconnect to the server
问题描述
我的 Tcpclient 没有正确断开连接,我使用的是客户端异步.
我想在服务器断开连接时自动重新连接.
什么是正确的路径?
My Tcpclient did not disconnect properly I am using Client async.
I want to reconnect again automatic when server disconnect.
What is correct path?
private void Connect_btn_Click(object sender, EventArgs e)
{
try
{
if (IsConnected == false)
{
constatus.Text = "Connecting.....";
newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//IPEndPoint iep = new IPEndPoint(IPAddress.Any, 20);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(IP), Convert.ToInt16(PORT));
newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
}
else
{
MessageBox.Show("Connection is Already Connected");
}
}
catch (Exception)
{
MessageBox.Show("Please Enter IPAddress and Port Address","Error",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
//This is Connected Function IASYNCHRESLT interface using call back
//Connected Function Call Back Asynch use in Connection button
void Connected(IAsyncResult iar)
{All Commands Inputs Send Fucntion Calling}
{
try
{
client = (Socket)iar.AsyncState;
client.EndConnect(iar);
this.Invoke(new viewStatus(setValue), "Connected");
//constatus.Text = "Connected To:" + client.RemoteEndPoint.ToString();
client.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
GetAllDateHide_performClick();
}
catch (SocketException)
{
ErrorConnecting();
}
}
这是断开代码
private void ButtonDisconnect_Click(object sender, EventArgs e)
{
try
{
client.Close();
constatus.Text = "Disconnected";
}
catch (Exception) { }
}
以及如何处理我将断开连接的 ObjectDisposed 异常
and how to handle the ObjectDisposed Exception i will disconnect
推荐答案
首先,我不确定您为什么直接使用套接字而不是使用 TcpClient (文档).有原因吗?因为 TcpClient 更干净.
First, I'm not sure why you're using a socket directly instead of using a TcpClient (documentation). Is there a reason? because TcpClient is cleaner.
第二,如果您已经在计划异步,为什么不使用 async-await
?
Second, if you're already planning for asynchrony why not use async-await
?
最后,我不建议直接从 GUI 进行网络操作.
Lastly, I won't recommend doing network operations directly from the GUI.
关于自动重新连接,我看到了 2 个选项.
About the automatic reconnection i see 2 options.
- 如果操作导致错误,则重新连接.
- 有一个落后的工人每隔一段时间尝试重新连接.
你还没有展示任何操作,所以我展示了我对第二个操作的看法:
You haven't showed any operations so I present my take on the second one:
public class TcpManager
{
private TcpClient _tcpClient;
public TcpManager()
{
_tcpClient = new TcpClient(AddressFamily.InterNetwork);
Task.Run(() => ConnectAsync());
}
private async Task ConnectAsync()
{
while (true)
{
if (!_tcpClient.Connected)
{
Console.WriteLine("Connecting...");
try
{
_tcpClient = new TcpClient(AddressFamily.InterNetwork);
await _tcpClient.ConnectAsync(IPAddress.Parse(IP), Convert.ToInt16(PORT));
await Task.Delay(TimeSpan.FromSeconds(5));
}
catch (SocketException e)
{
Console.WriteLine(e);
}
}
else
{
Console.WriteLine("Already Connected");
}
}
}
private void Close()
{
try
{
_tcpClient.Close();
_tcpClient = new TcpClient(AddressFamily.InterNetwork);
Console.WriteLine("Disconnected");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
这篇关于重新连接到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!