我有一台服务器,它会在非常不规则的时间段内发送一些数据,并在理想时间的每30秒内发送一次心跳。
我写了一个TCP客户端来连接到该服务器并读取数据。它工作正常,但是当网络出现问题并且服务器变得不可用时,我需要执行以下操作。
当客户端和服务器之间的连接失败时,我需要尝试重新连接到服务器(如果服务器在间隔后不可用,则以30秒间隔重复此过程三次,成功重新连接后我需要继续工作进程我需要显示服务器不可用的消息。)
我怎样才能做到这一点?请帮我。这是我的代码。
private void ServiceMethod(string Port, string Host)
{
try
{
//create a new client socket ...
m_socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
String szIPSelected = Host;
String szPort = Port;
int alPort = System.Convert.ToInt16(szPort, 10);
System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(szIPSelected);
System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, alPort);
//m_socClient = new Socket(remoteEndPoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
m_socClient.BeginConnect(remoteEndPoint, new AsyncCallback(OnClientConnect), null);
}
catch (SocketException se)
{
//Code To Handle Exception
}
catch (Exception ex)
{
}
}
public void OnClientConnect(IAsyncResult asyn)
{
try
{
Object objData = "Client Connected";
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
m_socClient.Send(byData);
TraceService("client Connected at " + m_socClient.RemoteEndPoint);
m_socClient.EndConnect(asyn);
WaitForData(m_socClient);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
}
catch (SocketException se)
{
// MessageBox.Show(se.Message);
}
}
public class CSocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[100];
}
public void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
if (pfnWorkerCallBack == null)
{
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
}
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = soc;
// now start to listen for any data...
soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
}
catch (SocketException se)
{
//MessageBox.Show(se.Message);
}
}
public void OnDataReceived(IAsyncResult asyn)
{
try
{
CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState;
//end receive...
int iRx = 0;
iRx = theSockId.thisSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
ASCIIEncoding asen = new ASCIIEncoding();
response = System.Convert.ToChar(System.Convert.ToUInt32("6", 16)).ToString();
m_socClient.Send(asen.GetBytes(response));
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
if (m_socClient.Connected)
{
WaitForData(m_socClient);
}
}
catch (SocketException se)
{
if (m_socClient.Connected)
{
WaitForData(m_socClient);
}
}
catch (Exception e)
{
//MessageBox.Show(e.Message);
if (m_socClient.Connected)
{
WaitForData(m_socClient);
}
}
}