最近做模擬雷達(dá)推送數(shù)據(jù)的項(xiàng)目,用一個(gè)軟件模擬幾百臺雷達(dá)往后端推送數(shù)據(jù),數(shù)據(jù)處理的代碼我就不貼了,主要是建立socket連接和斷線重連部分的代碼。主要是針對服務(wù)端斷開連接后,客戶端這邊要重現(xiàn)服務(wù)器。
我是先從數(shù)據(jù)庫讀取數(shù)據(jù),對數(shù)據(jù)封裝傳到后端,讀數(shù)據(jù)的時(shí)候用一個(gè)List存放數(shù)據(jù)庫的雷達(dá)設(shè)備名稱,
/// <summary>
/// 根據(jù)設(shè)備建立socket連接
/// </summary>
public static void DeviSocketDic()
{
for(int i = 0; i < Settings.DeviceNumList.Count; i++)
{
TcpClient tcp = Connect();
if (!DeviceSocket.ContainsKey(Settings.DeviceNumList[i]))
{
DeviceSocket.Add(Settings.DeviceNumList[i], tcp);
IPEndPoint localIEP = (IPEndPoint)tcp.Client.LocalEndPoint;
PortList.Add(localIEP.Port.ToString());
}
}
}
/// <summary>
/// TCP連接
/// </summary>
/// <returns></returns>
public static TcpClient Connect()
{
try
{
tcpc = new TcpClient();
tcpc.Connect(ip, int.Parse(port));//連接到服務(wù)
}
catch (Exception)
{
return null;
}
return tcpc;
}
public static Dictionary<string, TcpClient> DeviceSocket = new Dictionary<string, TcpClient>();
public static List<string> DeviceNumList = new List<string>();
private static TcpClient tcpc = null;
public static string ip = string.Empty;
public static string port = string.Empty;
以上代碼實(shí)現(xiàn)建立很多個(gè)socket連接存放到字典里面,變量定義我放在代碼后面了。
foreach (KeyValuePair<string, TcpClient> item in HTTPServer.DeviceSocket)
{
if (item.Value.Client.Poll(20, SelectMode.SelectRead) && item.Value.Client.Available == 0)
{
item.Value.Close();
HTTPServer.DeviceSocket[item.Key] = HTTPServer.Connect();
}
}
上面對字典遍歷的代碼我刪掉了一些,對控件判斷和顯示的部分,主要的就在這里面了,if對socket判斷,不存在就關(guān)閉連接,重新建連接寫到字典里面。數(shù)據(jù)處理部門就對字典遍歷選取設(shè)備號對應(yīng)的socket連接。項(xiàng)目里面我做了個(gè)定時(shí)300ms查詢一次連接是否還在定時(shí)器任務(wù)。代碼如下
public void ConnectStateTiming()
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = true;
timer.Interval = 300;//執(zhí)行間隔時(shí)間,單位為毫秒
timer.Start();
timer.Elapsed += new System.Timers.ElapsedEventHandler(FlashConnectState);
}