【发布时间】:2014-01-01 16:28:28
【问题描述】:
我的 Tcpclient 没有正确断开连接我正在使用客户端异步。
我想在服务器断开连接时自动重新连接。
什么是正确的路径?
这是连接代码
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 异常
【问题讨论】:
标签: c# networking tcp tcpclient