C# socket断线重连等异常情况处理 socket多线程C#异常异步 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 /// <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); } } }} 建议是每隔一秒(时间自己顶)向GPS发送一条数据等待确认,如果收不到可判断断开 代码看了一部分 有待提高. 比如你既然使用了异步 为什么还会出现while(true)呢http://www.cnblogs.com/chenxizhang/archive/2011/09/10/2172994.html看下这里很基础的东西..很不错另外断线重连是客户端的事..你是做服务的 无需担心 你只要try catch就行了.当他执行到catch 说明断线了 你是可以获取到断开的 socket 然后想如何操作 随便你 谁知道你报什么错?哪行语句报错?服务器程序在 release 方式下执行时,肯定会容错。错误了,结束服务就行了。断线重连是客户端(消息发起的一端)的事情,不是服务器的事情。 错误了,结束服务就行了 --> 如果发现是底层连接方面出现错误了,结束当前服务连接就行了客户端的重连会重新请求服务器的新的 Accept 操作。 SharpPcap 流量问题 页面大,速度慢,怎么办? 请问在VS2005的C#类中如何启动framework2.0? 求助下拉菜单点击事件-帮帮小D 用C#实现“结构数组”的问题 关于连接SQlSever 2000的问题!!帮帮忙啊!!急!!!! zswang在吗上次的问题:请问如何用什么代码能实现把运行的别人的程序最大化? 很好的学习网站 http://vod.52en.com/auto.asp?id=955834 :) SqlDataAdapter 如何填充DataSet ?看我的做法错在哪里? C# 如何解析RDF wpf 调试的时候老是这样,心都凉了,求解答 谁能搞定这个验证码
/// 读取数据
/// </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);
}
}
}
}