C# socket断线重连等异常情况处理

时间:2022-10-31 13:30:44
请教大家一个问题啊,现在做一个数据采集的软件,就是一个GPS模块通过GPRS以TCP的方式发送数据,我这边用socket异步多线程的方式(因为技术原因,采用的是一个GPS模块对应一个端口的方式)接收数据,现在数据都能接收存入数据库,请问如何解决例如断线重连这类异常的情况呢,比如说网络断了重新连接的话就报错。第一次贴代码,大家见谅


using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Configuration;
using System.Data.SqlClient;
using Mono.Security.Authenticode;
using Npgsql;

namespace GPSDA
{
    class Program
    {
        /// <summary>
        /// 车辆-端口
        /// </summary>
        public static Hashtable CarPortHashtable = new Hashtable();

        /// <summary>
        /// 本机IP
        /// </summary>
        public static IPAddress ServerIpAddress;

        /// <summary>
        /// 缓冲区大小
        /// </summary>
        public const int BUFFER_SIZE = 20 * 1024;

        private static byte[] buffers = new byte[BUFFER_SIZE];

        /// <summary> 
        /// 线程标识
        /// </summary>
        //public static ManualResetEvent allDone = new ManualResetEvent(false);

        /// <summary> 
        /// 线程标识
        /// </summary>
        //private static ManualResetEvent readDone = new ManualResetEvent(false);

        /// <summary>
        /// 线程标识池
        /// </summary>
        public static Hashtable AllDoneManualResetEvent = new Hashtable();

        /// <summary>
        /// 线程标识池
        /// </summary>
        public static Hashtable ReadDoneManualResetEvent = new Hashtable();

        /// <summary>
        /// GPGGA数据
        /// </summary>
        public static Hashtable GPGGAHashtable = new Hashtable();

        /// <summary>
        /// GPRMC数据
        /// </summary>
        public static Hashtable GPRMCHashtable = new Hashtable();

        private static string connsql =
            ConfigurationManager.ConnectionStrings["PortDBConnectStr"].ConnectionString.ToString();


        static void Main(string[] args)
        {
            //获取端口信息
            //GetCarIDPort();

            //string connpg = ConfigurationManager.ConnectionStrings["PgDBConnectStr"].ConnectionString.ToString();
            //NpgsqlConnection con=new NpgsqlConnection(connpg);
            //con.Open();

            //获取本机IP
            if (!IPAddress.TryParse(GetServerIP(), out ServerIpAddress))
            {
                Console.WriteLine("无法获取本机IP");
                return;
            }

            //对每一个端口进行监听,每一辆车对应一个端口
            //foreach (DictionaryEntry entry in CarPortHashtable)
            //{
            //    // 线程需要的参数赋值
            //    CarPort carPort = new CarPort();
            //    carPort.CarID = (int)entry.Key;
            //    carPort.Port = (int)entry.Value;

            //    ManualResetEvent allDone = new ManualResetEvent(false);
            //    ManualResetEvent readDone = new ManualResetEvent(false);

            //    AllDoneManualResetEvent.Add((int)entry.Key, allDone);
            //    ReadDoneManualResetEvent.Add((int)entry.Key, readDone);

            //    Thread thread = new Thread(BeginListen);
            //    thread.Name = carPort.CarID + "-" + carPort.Port + "";
            //    thread.IsBackground = true;
            //    thread.Start(carPort);

            //}

            // 线程需要的参数赋值
            CarPort carPort = new CarPort();
            carPort.CarID = 1;
            carPort.Port = 20110;
            ManualResetEvent allDone = new ManualResetEvent(false);
            ManualResetEvent readDone = new ManualResetEvent(false);
            AllDoneManualResetEvent.Add(1, allDone);
            ReadDoneManualResetEvent.Add(1, readDone);
            Thread thread = new Thread(BeginListen);
            thread.IsBackground = true;
            thread.Name = carPort.CarID + "-" + carPort.Port + "";
            thread.Start(carPort);

            Console.Read();
        }

        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="o">车辆-端口参数</param>
        public static void BeginListen(object o)
        {
            CarPort carport = (CarPort)o;

            IPEndPoint iep = new IPEndPoint(ServerIpAddress, carport.Port);
            //IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.1.217"), 20110);
            Socket mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            StateObject stateObjectAccept = new StateObject();//传递参数
            stateObjectAccept.workSocket = mSocket;
            stateObjectAccept.carID = carport.CarID;
            stateObjectAccept.port = carport.Port;
            try
            {
                mSocket.Bind(iep);
                mSocket.Listen(3);

                while (true)
                {
                    // Set the event to nonsignaled state. 
                    //allDone.Reset();
                    ((ManualResetEvent)AllDoneManualResetEvent[stateObjectAccept.carID]).Reset();

                    // Start an asynchronous socket to listen for connections. 
                    Console.WriteLine(DateTime.Now.ToString() + "\t" + stateObjectAccept.carID + "\t" +
                                      "Waiting for a connection...");
                    mSocket.BeginAccept(new AsyncCallback(AcceptCallback), stateObjectAccept);
                    // Wait until a connection is made before continuing. 
                    //allDone.WaitOne();
                    ((ManualResetEvent)AllDoneManualResetEvent[stateObjectAccept.carID]).WaitOne();

                }
            }
            catch (Exception e)
            {
                Console.WriteLine("BeginListen"+"------>"+e.Message);

            }
     
        }

        /// <summary>
        /// 异步操作回调函数
        /// </summary>
        /// <param name="ar">一步操作状态</param>
        public static void AcceptCallback(IAsyncResult ar)
        {
            // Get the socket that handles the client request. 
            //Socket listener = (Socket)ar.AsyncState;
            //Socket handler = listener.EndAccept(ar);
            try
            {
                StateObject stateObjectRead = (StateObject)ar.AsyncState;
                Socket handler = stateObjectRead.workSocket.EndAccept(ar);
                stateObjectRead.workSocket = handler;

                // Signal the main thread to continue. 
                //allDone.Set();
                ((ManualResetEvent)AllDoneManualResetEvent[stateObjectRead.carID]).Set();
                while (true)
                {
                    //readDone.Reset();
                    ((ManualResetEvent)ReadDoneManualResetEvent[stateObjectRead.carID]).Reset();

                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "\t" + stateObjectRead.carID + "\t" + "BeginReceive...");
                    handler.BeginReceive(buffers, 0, BUFFER_SIZE, 0, new AsyncCallback(ReadCallback),
                        stateObjectRead);

                    //readDone.WaitOne();
                    ((ManualResetEvent)ReadDoneManualResetEvent[stateObjectRead.carID]).WaitOne();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("AcceptCallback" + "------>" + e.Message);

            }
        }

       

6 个解决方案

#1


 /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="ar"></param>
        public static void ReadCallback(IAsyncResult ar)
        {
            try
            {
                String content = String.Empty;
                // Retrieve the state object and the handler socket 
                // from the asynchronous state object. 
                StateObject state = (StateObject)ar.AsyncState;
                Socket handler = state.workSocket;

                // Read data from the client socket.  
                int bytesRead = handler.EndReceive(ar);

                //readDone.Set();
                ((ManualResetEvent)ReadDoneManualResetEvent[state.carID]).Set();

                if (bytesRead > 0)
                {
                    //// There  might be more data, so store the data received so far. 
                    //state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
                    //// Check for end-of-file tag. If it is not there, read  
                    //// more data. 
                    //content = state.sb.ToString();

                    byte[] receivedata = new byte[bytesRead];
                    Array.Copy(buffers, 0, receivedata, 0, bytesRead);
                    content = System.Text.Encoding.Default.GetString(receivedata);
                    #region 两条分开发送
                    //if (content.IndexOf("\r\n") > -1 && ((content.IndexOf("$GPGGA") > content.IndexOf("\r\n")) || (content.IndexOf("$GPRMC") > content.IndexOf("\r\n"))))
                    //{
                    //    //Console.WriteLine("CarID:{0}", state.carID);
                    //    // All the data has been read from the  
                    //    // client. Display it on the console. 
                    //    Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
                    //    NMEA nmea = new NMEA();
                    //    string type = nmea.Parse(content);
                    //    switch (type)
                    //    {
                    //        case "failure":
                    //            break;
                    //        case "GPGGA":
                    //            GPGGA gpgga = nmea.GpggaData;
                    //            // 与hashtable中的GPRMC比较时间
                    //            if (GPRMCHashtable[state.carID] != null)
                    //            {
                    //                GPRMC bGprmc = (GPRMC)GPRMCHashtable[state.carID];
                    //                TimeSpan sub = bGprmc.DateTime.Subtract(gpgga.DateTime);
                    //                if (Math.Abs(sub.TotalSeconds) < 0.5)
                    //                {
                    //                    // 是同一时间的数据则坐标转换写入数据库
                    //                    DatabaseManipulation(gpgga, bGprmc, state.carID);
                    //                }
                    //                GPGGAHashtable[state.carID] = gpgga;
                    //            }
                    //            break;
                    //        case "GPRMC":
                    //            GPRMC gprmc = nmea.GprmcData;
                    //            // 与hashtable中的GPRMC比较时间
                    //            if (GPGGAHashtable[state.carID] != null)
                    //            {
                    //                GPGGA bGpgga = (GPGGA)GPGGAHashtable[state.carID];
                    //                TimeSpan sub = bGpgga.DateTime.Subtract(gprmc.DateTime);
                    //                if (Math.Abs(sub.TotalSeconds) < 0.5)
                    //                {
                    //                    // 是同一时间的数据则坐标转换写入数据库
                    //                    DatabaseManipulation(bGpgga, gprmc, state.carID);
                    //                }
                    //                GPRMCHashtable[state.carID] = gprmc;
                    //            }
                    //            break;
                    //        default:
                    //            break;
                    //    }


                    //}
                    //else
                    //{
                    //    // Not all data received. Get more. 
                    //    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                    //} 
                    #endregion

                    #region 四信 两条数据同时发送过来的
                    Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
                    if (content.IndexOf("\r\n") > -1 && (content.LastIndexOf("\r\n") > content.IndexOf("\r\n")) && content.IndexOf("$GPGGA") > -1 && content.IndexOf("$GPRMC") > -1)
                    {
                        //Console.WriteLine("CarID:{0}", state.carID);
                        // All the data has been read from the  
                        // client. Display it on the console. 
                        string strGPGGA = content.Substring(0, content.IndexOf("$GPRMC"));
                        string strGPRMC = content.Substring(content.IndexOf("$GPRMC"));
                        NMEA nmea = new NMEA();
                        string type1 = nmea.Parse(strGPGGA);
                        string type2 = nmea.Parse(strGPRMC);
                        //if (String.Equals("failure", type1) || String.Equals("failure", type2))
                        //{
                        //    return;
                        //}
                        GPGGA gpgga = nmea.GpggaData;
                        GPRMC gprmc = nmea.GprmcData;
                        // 是同一时间的数据则坐标转换写入数据库
                        DatabaseManipulation(gpgga, gprmc, state.carID);
                    }
                    //else
                    //{
                    //    // Not all data received. Get more. 
                    //    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                    //}
                    #endregion
                    handler.Blocking = false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ReadCallback" + "------>" + ex.Message);
            }
        }

        /// <summary>
        /// 将数据写入数据库中
        /// </summary>
        /// <param name="gpgga">GPGGA的数据</param>
        /// <param name="gprmc">GPRMC的数据</param>
        private static void DatabaseManipulation(GPGGA gpgga, GPRMC gprmc, int carid)
        {
            PositionData pos = new PositionData();
            //时间
            pos.time = gpgga.DateTime;

            //检查是否为空
            if (gprmc.Latitude == null || gprmc.Longitude == null || gpgga.HighAltitude == null || gpgga.RelativeHeight == null)
            {
                return;
            }
            //方向 
            pos.direction = gprmc.Direction;

            // 转换坐标  
            //x-椭球参考面=海拔高-椭球面相对大地水准面的高度
            double height = gpgga.HighAltitude - gpgga.RelativeHeight;
            //空间大地坐标系转换为空间直角坐标系
            CoordateXYZ coorXYZ = CoordinateTransform.ParseNMEA(gprmc.Latitude, gprmc.Longitude, height);

            pos.x = coorXYZ.x;
            pos.y = coorXYZ.y;
            pos.z = coorXYZ.z;

            pos.carid = carid;

            pos.speed = gprmc.Speed;

            pos.hdop = gpgga.Hdop;

            int row = PgHelper.InsertData(pos);
        }

        /// <summary>
        /// 结构体  车辆ID-端口号
        /// </summary>
        public struct CarPort
        {
            /// <summary>
            /// 车辆编号
            /// </summary>
            public int CarID;

            /// <summary>
            /// 端口号
            /// </summary>
            public int Port;
        }

        /// <summary>
        /// 获取服务器本机的IP
        /// </summary>
        /// <returns>IPv4地址,string类型</returns>
        public static string GetServerIP()
        {
            try
            {
                string HostName = Dns.GetHostName();
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception e)
            {
                Console.WriteLine("获取本机IP失败" + e.Message);
                return "";
            }
        }

        /// <summary>
        /// 读取配置文件,从数据库中获取车辆ID及对应的端口号,以进行监听
        /// </summary>
        private static void GetCarIDPort()
        {
            DataSet ds = new DataSet();
            try
            {

                SqlConnection conn = new SqlConnection(connsql);
                conn.Open();
                string selectsql = "select MineCarID,Port from MineCarInfo";
                SqlCommand cmd = new SqlCommand(selectsql, conn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                int ID = (int)ds.Tables[0].Rows[i][0];
                int Port = (int)ds.Tables[0].Rows[i][1];
                CarPortHashtable.Add(ID, Port);
            }
        }
    }
}

#2


建议是每隔一秒(时间自己顶)向GPS发送一条数据等待确认,如果收不到可判断断开

#3


代码看了一部分 有待提高. 比如你既然使用了异步 为什么还会出现while(true)呢

http://www.cnblogs.com/chenxizhang/archive/2011/09/10/2172994.html

看下这里很基础的东西..很不错

另外断线重连是客户端的事..你是做服务的 无需担心  你只要try catch就行了.

当他执行到catch 说明断线了 你是可以获取到断开的 socket  然后想如何操作 随便你

#4


引用 楼主 whu_xxie 的回复:
请教大家一个问题啊,现在做一个数据采集的软件,就是一个GPS模块通过GPRS以TCP的方式发送数据,我这边用socket异步多线程的方式(因为技术原因,采用的是一个GPS模块对应一个端口的方式)接收数据,现在数据都能接收存入数据库,请问如何解决例如断线重连这类异常的情况呢,比如说网络断了重新连接的话就报错。第一次贴代码,大家见谅
       

谁知道你报什么错?哪行语句报错?

服务器程序在 release 方式下执行时,肯定会容错。错误了,结束服务就行了。断线重连是客户端(消息发起的一端)的事情,不是服务器的事情。

#5


错误了,结束服务就行了   -->   如果发现是底层连接方面出现错误了,结束当前服务连接就行了

客户端的重连会重新请求服务器的新的 Accept 操作。

#6


代码粘的有点儿多,我是来学习的 C# socket断线重连等异常情况处理

#1


 /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="ar"></param>
        public static void ReadCallback(IAsyncResult ar)
        {
            try
            {
                String content = String.Empty;
                // Retrieve the state object and the handler socket 
                // from the asynchronous state object. 
                StateObject state = (StateObject)ar.AsyncState;
                Socket handler = state.workSocket;

                // Read data from the client socket.  
                int bytesRead = handler.EndReceive(ar);

                //readDone.Set();
                ((ManualResetEvent)ReadDoneManualResetEvent[state.carID]).Set();

                if (bytesRead > 0)
                {
                    //// There  might be more data, so store the data received so far. 
                    //state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
                    //// Check for end-of-file tag. If it is not there, read  
                    //// more data. 
                    //content = state.sb.ToString();

                    byte[] receivedata = new byte[bytesRead];
                    Array.Copy(buffers, 0, receivedata, 0, bytesRead);
                    content = System.Text.Encoding.Default.GetString(receivedata);
                    #region 两条分开发送
                    //if (content.IndexOf("\r\n") > -1 && ((content.IndexOf("$GPGGA") > content.IndexOf("\r\n")) || (content.IndexOf("$GPRMC") > content.IndexOf("\r\n"))))
                    //{
                    //    //Console.WriteLine("CarID:{0}", state.carID);
                    //    // All the data has been read from the  
                    //    // client. Display it on the console. 
                    //    Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
                    //    NMEA nmea = new NMEA();
                    //    string type = nmea.Parse(content);
                    //    switch (type)
                    //    {
                    //        case "failure":
                    //            break;
                    //        case "GPGGA":
                    //            GPGGA gpgga = nmea.GpggaData;
                    //            // 与hashtable中的GPRMC比较时间
                    //            if (GPRMCHashtable[state.carID] != null)
                    //            {
                    //                GPRMC bGprmc = (GPRMC)GPRMCHashtable[state.carID];
                    //                TimeSpan sub = bGprmc.DateTime.Subtract(gpgga.DateTime);
                    //                if (Math.Abs(sub.TotalSeconds) < 0.5)
                    //                {
                    //                    // 是同一时间的数据则坐标转换写入数据库
                    //                    DatabaseManipulation(gpgga, bGprmc, state.carID);
                    //                }
                    //                GPGGAHashtable[state.carID] = gpgga;
                    //            }
                    //            break;
                    //        case "GPRMC":
                    //            GPRMC gprmc = nmea.GprmcData;
                    //            // 与hashtable中的GPRMC比较时间
                    //            if (GPGGAHashtable[state.carID] != null)
                    //            {
                    //                GPGGA bGpgga = (GPGGA)GPGGAHashtable[state.carID];
                    //                TimeSpan sub = bGpgga.DateTime.Subtract(gprmc.DateTime);
                    //                if (Math.Abs(sub.TotalSeconds) < 0.5)
                    //                {
                    //                    // 是同一时间的数据则坐标转换写入数据库
                    //                    DatabaseManipulation(bGpgga, gprmc, state.carID);
                    //                }
                    //                GPRMCHashtable[state.carID] = gprmc;
                    //            }
                    //            break;
                    //        default:
                    //            break;
                    //    }


                    //}
                    //else
                    //{
                    //    // Not all data received. Get more. 
                    //    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                    //} 
                    #endregion

                    #region 四信 两条数据同时发送过来的
                    Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
                    if (content.IndexOf("\r\n") > -1 && (content.LastIndexOf("\r\n") > content.IndexOf("\r\n")) && content.IndexOf("$GPGGA") > -1 && content.IndexOf("$GPRMC") > -1)
                    {
                        //Console.WriteLine("CarID:{0}", state.carID);
                        // All the data has been read from the  
                        // client. Display it on the console. 
                        string strGPGGA = content.Substring(0, content.IndexOf("$GPRMC"));
                        string strGPRMC = content.Substring(content.IndexOf("$GPRMC"));
                        NMEA nmea = new NMEA();
                        string type1 = nmea.Parse(strGPGGA);
                        string type2 = nmea.Parse(strGPRMC);
                        //if (String.Equals("failure", type1) || String.Equals("failure", type2))
                        //{
                        //    return;
                        //}
                        GPGGA gpgga = nmea.GpggaData;
                        GPRMC gprmc = nmea.GprmcData;
                        // 是同一时间的数据则坐标转换写入数据库
                        DatabaseManipulation(gpgga, gprmc, state.carID);
                    }
                    //else
                    //{
                    //    // Not all data received. Get more. 
                    //    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                    //}
                    #endregion
                    handler.Blocking = false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ReadCallback" + "------>" + ex.Message);
            }
        }

        /// <summary>
        /// 将数据写入数据库中
        /// </summary>
        /// <param name="gpgga">GPGGA的数据</param>
        /// <param name="gprmc">GPRMC的数据</param>
        private static void DatabaseManipulation(GPGGA gpgga, GPRMC gprmc, int carid)
        {
            PositionData pos = new PositionData();
            //时间
            pos.time = gpgga.DateTime;

            //检查是否为空
            if (gprmc.Latitude == null || gprmc.Longitude == null || gpgga.HighAltitude == null || gpgga.RelativeHeight == null)
            {
                return;
            }
            //方向 
            pos.direction = gprmc.Direction;

            // 转换坐标  
            //x-椭球参考面=海拔高-椭球面相对大地水准面的高度
            double height = gpgga.HighAltitude - gpgga.RelativeHeight;
            //空间大地坐标系转换为空间直角坐标系
            CoordateXYZ coorXYZ = CoordinateTransform.ParseNMEA(gprmc.Latitude, gprmc.Longitude, height);

            pos.x = coorXYZ.x;
            pos.y = coorXYZ.y;
            pos.z = coorXYZ.z;

            pos.carid = carid;

            pos.speed = gprmc.Speed;

            pos.hdop = gpgga.Hdop;

            int row = PgHelper.InsertData(pos);
        }

        /// <summary>
        /// 结构体  车辆ID-端口号
        /// </summary>
        public struct CarPort
        {
            /// <summary>
            /// 车辆编号
            /// </summary>
            public int CarID;

            /// <summary>
            /// 端口号
            /// </summary>
            public int Port;
        }

        /// <summary>
        /// 获取服务器本机的IP
        /// </summary>
        /// <returns>IPv4地址,string类型</returns>
        public static string GetServerIP()
        {
            try
            {
                string HostName = Dns.GetHostName();
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception e)
            {
                Console.WriteLine("获取本机IP失败" + e.Message);
                return "";
            }
        }

        /// <summary>
        /// 读取配置文件,从数据库中获取车辆ID及对应的端口号,以进行监听
        /// </summary>
        private static void GetCarIDPort()
        {
            DataSet ds = new DataSet();
            try
            {

                SqlConnection conn = new SqlConnection(connsql);
                conn.Open();
                string selectsql = "select MineCarID,Port from MineCarInfo";
                SqlCommand cmd = new SqlCommand(selectsql, conn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                int ID = (int)ds.Tables[0].Rows[i][0];
                int Port = (int)ds.Tables[0].Rows[i][1];
                CarPortHashtable.Add(ID, Port);
            }
        }
    }
}

#2


建议是每隔一秒(时间自己顶)向GPS发送一条数据等待确认,如果收不到可判断断开

#3


代码看了一部分 有待提高. 比如你既然使用了异步 为什么还会出现while(true)呢

http://www.cnblogs.com/chenxizhang/archive/2011/09/10/2172994.html

看下这里很基础的东西..很不错

另外断线重连是客户端的事..你是做服务的 无需担心  你只要try catch就行了.

当他执行到catch 说明断线了 你是可以获取到断开的 socket  然后想如何操作 随便你

#4


引用 楼主 whu_xxie 的回复:
请教大家一个问题啊,现在做一个数据采集的软件,就是一个GPS模块通过GPRS以TCP的方式发送数据,我这边用socket异步多线程的方式(因为技术原因,采用的是一个GPS模块对应一个端口的方式)接收数据,现在数据都能接收存入数据库,请问如何解决例如断线重连这类异常的情况呢,比如说网络断了重新连接的话就报错。第一次贴代码,大家见谅
       

谁知道你报什么错?哪行语句报错?

服务器程序在 release 方式下执行时,肯定会容错。错误了,结束服务就行了。断线重连是客户端(消息发起的一端)的事情,不是服务器的事情。

#5


错误了,结束服务就行了   -->   如果发现是底层连接方面出现错误了,结束当前服务连接就行了

客户端的重连会重新请求服务器的新的 Accept 操作。

#6


代码粘的有点儿多,我是来学习的 C# socket断线重连等异常情况处理