各位大神好:
想請問讀卡機透過tcpip模組連線,想寫程式讀1621port(soyal)傳來的資料,因為目前只有一台,但是以後想說有多台,先用其他電腦主機模擬..使用非同步與多執行緒處理,但如果用電腦主機(有個連線程式跟ConsoleClient連線)模擬讀卡機,大概過5小時或過1天,連線就與主程式中斷連線,想請問要怎麼有機制自動重新連線呢?
以下ip:166.187是用電腦模擬卡機跟主程式連線 ip:192.168.20.15是讀卡機跟主程式連線
謝謝
主程式ConsoleClient
public void ConnectToserver()
{
int numberOfClients = 0;
//預設主機IP
string[] arrayIP = new string[] {"192.168.20.15", "192.168.20.16", "192.168.20.187" };
//先建立IPAddress物件,IP為欲連線主機之IP
for (int i = 0; i < arrayIP.Length; i++)
{
string hostIP = arrayIP[i];
IPAddress ipa = IPAddress.Parse(hostIP);
//建立IPEndPoint
IPEndPoint ipe = new IPEndPoint(ipa, 1621);
//先建立一個TCPClient
TcpClient tcpClient = new TcpClient();
try
{
Console.WriteLine("讀卡機主機IP" + ipa.ToString());
Console.WriteLine("連線至讀卡機主機中...\n");
if (!tcpClient.ConnectAsync(ipa, 1621).Wait(1000)) //5s
{
Console.WriteLine(ipa+ "連線失敗!");
}
if (tcpClient.Connected)
{
MultipleClient mutipleclient = new MultipleClient(tcpClient,ipa.ToString());
Thread myThread = new Thread(new ThreadStart(mutipleclient.Communicate));
numberOfClients += 1;
myThread.IsBackground = true;
myThread.Start();
myThread.Name = tcpClient.Client.RemoteEndPoint.ToString();
}
else
{
Console.WriteLine("連線失敗!");
}
}
catch (Exception ex)
{
tcpClient.Close();
Console.WriteLine(ex.Message);
}
} //for loop
Console.Read();
}
MultipleClient 類別
private TcpClient mTcpClient;
private String ip;
public MultipleClient(TcpClient _tcpClient,String ip) /
{
this.mTcpClient = _tcpClient;
this.ip = ip;
}
public void Communicate()
{
try
{
Console.WriteLine("連線成功aa"+this.ip.ToString());
CommunicationBasic cb = new CommunicationBasic();
Byte[] sendmessage = new byte[] { 0x7e, 0x04, 0x01, 0x25, 0xdb, 0x01 }; //送指令過去 看能不能讀卡
// while (true)
//{
cb.SendMsg(sendmessage, this.mTcpClient);
Console.WriteLine("TX:" + staticClass.ToHexString(sendmessage, sendmessage.Length)); //靜態類別不用new
string[] array = cb.ReceiveMsg(this.mTcpClient);
Console.WriteLine("RX:" +array[0]); //卡機回覆的資訊,如果沒回覆會卡住
Console.WriteLine("字串長度:"+array[1]);
//}
}
catch
{
Console.WriteLine("伺服器端強制關閉連線!" + this.ip.ToString());
this.mTcpClient.Close();
}
}
自動重新連線包含兩個功能,判斷是否斷線,判斷是否重新連線
1.我認為比較有效的方式是寫thread固定時間丟資料,跳出Exception就一定是斷線
2.寫thread查參數判斷是否重連,除了斷線也有可能其他原因需要重連