C# 实现客户端Socket断开后重新连接。
【摘要】
思路:使用System.Threading.Timer类每秒检测一次是否连接,如果没有处于连接状态,则尝试连接一次,如果连接失败,则将异常信息捕捉,并记录日志,然后Sleep2秒,再尝试连接,一直重复连接的步骤。
System.Threading.Timer timer = null; private void BtnConnect...
思路:使用System.Threading.Timer类每秒检测一次是否连接,如果没有处于连接状态,则尝试连接一次,如果连接失败,则将异常信息捕捉,并记录日志,然后Sleep2秒,再尝试连接,一直重复连接的步骤。
-
System.Threading.Timer timer = null;
-
private void BtnConnect_Click(object sender, RoutedEventArgs e)
-
{
-
-
timer = new Timer(new TimerCallback(TimerCall),null,Timeout.Infinite,1000);
-
timer.Change(0, 1000);
-
}
-
private void TimerCall(object obj)
-
{
-
if (!IsSocketConnected(socketWatch))
-
{
-
this.Dispatcher.Invoke(new Action(() =>
-
{
-
string connectIP = txtIP.Text;
-
string port = txtPort.Text;
-
-
try
-
{
-
socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
-
IPAddress address = IPAddress.Parse(connectIP);
-
socketWatch.Connect(address, int.Parse(port));
-
threadWatch = new Thread(RecMsg);
-
threadWatch.IsBackground = true;
-
threadWatch.Start();
-
}
-
catch
-
{ Thread.Sleep(2000); }
-
}));
-
-
}
-
}
-
private bool IsSocketConnected(Socket socket)
-
{
-
lock (this)
-
{
-
bool ConnectState = true;
-
bool state = socket.Blocking;
-
try
-
{
-
byte[] temp = new byte[1];
-
socket.Blocking = false;
-
socket.Send(temp, 0, 0);
-
ConnectState = true;
-
}
-
catch (SocketException e)
-
{
-
if (e.NativeErrorCode.Equals(10035)) //仍然是connect的
-
ConnectState = true;
-
else
-
ConnectState = false;
-
}
-
finally
-
{
-
socket.Blocking = state;
-
}
-
return ConnectState;
-
}
-
}
文章来源: wanghao.blog.csdn.net,作者:AI浩,版权归原作者所有,如需转载,请联系作者。
原文链接:wanghao.blog.csdn.net/article/details/113772225
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)