欢迎您的来访!有源码,好建站(www.codehy.com)源码海洋源码网为您提供快速建站平台.
当前位置: 首页 > 行业资讯 > c# .net 资料 >

C#使用TCPClient客户端断线重连服务器

时间:2021-07-11 23:33来源:未知 作者:admin 点击:
最近做模拟雷达推送数据的项目,用一个软件模拟几百台雷达往后端推送数据,数据处理的代码我就不贴了,主要是建立socket连接和断线重连部分的代码。主要是针对服务端断开连接后,客户端这边要重现服务器。 我是先从数据库读取数据,对数据封装传到后端,读数

 最近做模拟雷达推送数据的项目,用一个软件模拟几百台雷达往后端推送数据,数据处理的代码我就不贴了,主要是建立socket连接和断线重连部分的代码。主要是针对服务端断开连接后,客户端这边要重现服务器。

 
我是先从数据库读取数据,对数据封装传到后端,读数据的时候用一个List存放数据库的雷达设备名称,
/// <summary>
    /// 根据设备建立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));//连接到服务   
           
        }
        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;
 
     以上代码实现建立很多个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判断,不存在就关闭连接,重新建连接写到字典里面。数据处理部门就对字典遍历选取设备号对应的socket连接。项目里面我做了个定时300ms查询一次连接是否还在定时器任务。代码如下
public void ConnectStateTiming()
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = true;
timer.Interval = 300;//执行间隔时间,单位为毫秒
timer.Start();
timer.Elapsed += new System.Timers.ElapsedEventHandler(FlashConnectState);
}
 
(责任编辑:admin)本文地址:http://www.codehy.com/info/net/2021/0711/22471.html

推荐资讯