思路:使用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;
}
}
(責任編輯:admin)本文地址:http://m.bmm520.net/info/net/2021/0711/22467.html