/// <summary> /// 添加远程连接 /// </summary> /// <param name="strIpAddress">远程连接地址</param> /// <param name="port">远程连接端口</param> public void Add(string strIpAddress, int port) { #region [判断要连接的列表中是否存在] SocketPacket spCollect; for (int i = 0; i < m_socketClientList.Count; i++) { spCollect = (SocketPacket)m_socketClientList[i]; if (spCollect.IpAddress.Equals(strIpAddress) && spCollect.ClientPort.Equals(port)) { return; } } spCollect = null; #endregion [判断要连接的列表中是否存在] #region [添加到要连接的服务器列表中] SocketPacket sp = new SocketPacket(); sp.IpAddress = strIpAddress; sp.ClientPort = port; sp.ErrorShow = false; sp.State = 0; m_socketClientList.Add(sp); #endregion [添加到要连接的服务器列表中] //开始连接远程服务器 StartClient(sp); }
/// <summary> /// 开始连接远程服务器 /// </summary> /// <param name="socketPacket">要连接的远程服务器包</param> private void StartClient(SocketPacket socketPacket) { try { //设置指定的网络地址和端口号 IPAddress ipAddress = IPAddress.Parse(socketPacket.IpAddress); IPEndPoint remoteEP = new IPEndPoint(ipAddress, socketPacket.ClientPort); // 创建一个TCP/IP套接字对象. socketPacket.CurrentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 对远程主机开始异步连接. socketPacket.CurrentSocket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), socketPacket); } catch (SocketException e) { try { if (socketPacket.CurrentSocket != null) { socketPacket.CurrentSocket.Close(); socketPacket.CurrentSocket = null; } if (socketPacket.State == 1 && socketPacket.ErrorShow == false) { ErrorMessage(30001, e.StackTrace, "[Base_SocketClient:StartClient]", socketPacket.IpAddress + "未连接"); socketPacket.ErrorShow = true; } socketPacket.State = 2; } catch { } } catch (Exception ee) { } }
/// <summary> /// 挂起等待接收数据线程 /// </summary> /// <param name="socketPacket">远程连接对象包</param> private void WaitForData(SocketPacket socketPacket) { try { if (m_pfnCallBack == null) { m_pfnCallBack = new AsyncCallback(OnDataReceived); } // 开始异步获取数据 socketPacket.DataBuffer = new byte[socketPacket.DataLength]; socketPacket.CurrentSocket.BeginReceive(socketPacket.DataBuffer, 0, socketPacket.DataBuffer.Length, SocketFlags.None, m_pfnCallBack, socketPacket); } catch (SocketException se) { try { if (socketPacket.CurrentSocket != null) { socketPacket.CurrentSocket.Close(); socketPacket.CurrentSocket = null; } if ((socketPacket.State == 0 || socketPacket.State == 2) && socketPacket.ErrorShow == false) { ErrorMessage(30003, se.StackTrace, "[Base_SocketClient:WaitForData]", socketPacket.IpAddress + "未连接"); socketPacket.ErrorShow = true; } } catch { } } catch (Exception ee) { } }
/// <summary> /// 重新连接远程主机 /// </summary> private void Repeat() { while (true) { try { for (int i = 0; i < m_socketClientList.Count; i++) { SocketPacket s = (SocketPacket)m_socketClientList[i]; if (s.CurrentSocket == null || (s.CurrentSocket.Connected == false && s.State != 1)) { if (s.CurrentSocket != null) { s.CurrentSocket.Close(); s.CurrentSocket = null; } s.State = 1; StartClient(s); } } } catch { } finally { //3s后重新连接 Thread.Sleep(3000); } } }
/// <summary> /// 结束挂起的异步发送 /// </summary> /// <param name="ar">异步操作对象</param> private void SendCallback(IAsyncResult ar) { SocketPacket sp_SendCallbace = new SocketPacket(); try { sp_SendCallbace = (SocketPacket)ar.AsyncState; sp_SendCallbace.CurrentSocket.EndSend(ar); } catch (SocketException e) { try { if (sp_SendCallbace.CurrentSocket != null) { sp_SendCallbace.CurrentSocket.Close(); sp_SendCallbace.CurrentSocket = null; } if (sp_SendCallbace.State == 2 && !sp_SendCallbace.IpAddress.Equals("") && sp_SendCallbace.ErrorShow == false) { ErrorMessage(30005, e.StackTrace, "[Base_SocketClient:SendCallback]", sp_SendCallbace.IpAddress + "未连接"); sp_SendCallbace.ErrorShow = true; } } catch { } } catch (Exception ee) { } }
/// <summary> /// 结束挂起的连接请求 /// </summary> /// <param name="ar">异步调用对象</param> private void ConnectCallback(IAsyncResult ar) { //获取异步操作对象 SocketPacket socketPacket = (SocketPacket)ar.AsyncState; try { // 与远程主机连接完成 socketPacket.CurrentSocket.EndConnect(ar); if (socketPacket != null) { socketPacket.State = 2; if (socketPacket.CurrentSocket != null && socketPacket.CurrentSocket.Connected) { ErrorMessage(30007, "", "[Base_SocketClient:ConnectCallback]", socketPacket.IpAddress + "已连接"); socketPacket.ErrorShow = false; //等待接收数据 WaitForData(socketPacket); } } } catch (SocketException e) { try { if (socketPacket.CurrentSocket != null) { socketPacket.CurrentSocket.Close(); socketPacket.CurrentSocket = null; } if (socketPacket.State == 1 && socketPacket.ErrorShow == false) { ErrorMessage(30002, e.StackTrace, "[Base_SocketClient:ConnectCallback]", socketPacket.IpAddress + "未连接"); socketPacket.ErrorShow = true; } } catch { } } catch (Exception ee) { } finally { if (socketPacket != null) { socketPacket.State = 2; // if (socketPacket.CurrentSocket != null && socketPacket.CurrentSocket.Connected) // { // ErrorMessage(30007, "", "[Base_SocketClient:ConnectCallback]", socketPacket.IpAddress + "已连接"); // socketPacket.ErrorShow = false; // //等待接收数据 // WaitForData(socketPacket); // } } } }
/// <summary> /// /// </summary> /// <param name="hostBacker"></param> /// <param name="strpath"></param> /// <param name="configpath"></param> /// <param name="memStation"></param> public TcpClientUpdateTimer(HostBack.DataSave sqlSave, string strpath, string configpath, SocketPacket[] socketPackets) { this.sqlSave = sqlSave; this.TcpClientXmlFilePath = System.Windows.Forms.Application.StartupPath.ToString() + @"\" + strpath; this.StationConfigFilePath = System.Windows.Forms.Application.StartupPath.ToString() + @"\" + configpath; this.socketPackets = socketPackets; timeTcpChange.Interval = 5000; timeTcpChange.AutoReset = true; timeTcpChange.Elapsed += new System.Timers.ElapsedEventHandler(timeTcpChange_Elapsed); }
/// <summary> /// 结束挂起的等待接收数据线程 /// </summary> /// <param name="asyn">异步调用对象</param> private void OnDataReceived(IAsyncResult asyn) { SocketPacket socketPacket_Received = null; try { socketPacket_Received = (SocketPacket)asyn.AsyncState; int iRx = socketPacket_Received.CurrentSocket.EndReceive(asyn); if (iRx > 0)//屏蔽无效的空字节qyz 2012-11-30 { // 获取得到的字符 byte[] bytes = new byte[iRx]; for (int i = 0; i < iRx; i++) { bytes[i] = socketPacket_Received.DataBuffer[i]; } //调用数据获取事件 DataReceivedByAddress(bytes, socketPacket_Received.IpAddress); } } catch (SocketException se) { try { if (socketPacket_Received.CurrentSocket != null) { socketPacket_Received.CurrentSocket.Close(); socketPacket_Received.CurrentSocket = null; } if ((socketPacket_Received.State == 0 || socketPacket_Received.State == 2) && socketPacket_Received.ErrorShow == false) { ErrorMessage(30004, se.StackTrace, "[Base_SocketClient:WaitForData]", socketPacket_Received.IpAddress + "未连接"); socketPacket_Received.ErrorShow = true; } } catch { } } catch (Exception ee) { } finally { if (socketPacket_Received != null) { //继续等待数据 WaitForData(socketPacket_Received); } } }
/// <summary> /// 开始发送数据 /// </summary> /// <param name="bytes">发送字节</param> /// <param name="strIpAddress">发送的地址</param> /// <param name="port">发送的端口</param> public void Send(byte[] bytes, string strIpAddress, int port) { SocketPacket spCollect = new SocketPacket(); try { for (int i = 0; i < m_socketClientList.Count; i++) { spCollect = (SocketPacket)m_socketClientList[i]; if (spCollect.IpAddress.Equals(strIpAddress) && spCollect.ClientPort.Equals(port)) { //开始异步发送数据 //if (spCollect.CurrentSocket != null) //{ // spCollect.CurrentSocket.SendTimeout = 1800; // spCollect.CurrentSocket.Blocking = false; // spCollect.ReviceCount++; // spCollect.CurrentSocket.BeginSend(bytes, 0, bytes.Length, 0, new AsyncCallback(SendCallback), spCollect); //} //break; spCollect.CurrentSocket.BeginSend(bytes, 0, bytes.Length, 0, new AsyncCallback(SendCallback), spCollect); break; } } } catch (SocketException ee) { try { if (spCollect.CurrentSocket != null) { spCollect.CurrentSocket.Close(); spCollect.CurrentSocket = null; } if (spCollect.State == 2 && !spCollect.IpAddress.Equals("") && spCollect.ErrorShow == false) { ErrorMessage(30005, ee.StackTrace, "[Base_SocketClient:Send]", spCollect.IpAddress + "未连接"); spCollect.ErrorShow = true; } } catch { } } catch (Exception e) { } }
/// <summary> /// 初始化网络客户端连接 /// </summary> /// <param name="socketPackets"></param> /// <param name="iMark"></param> public void InitTcpClientPort(SocketPacket[] socketPackets, int iMark) { InitSocket(socketPackets); if (socketArrayList == null) { socketArrayList = new ArrayList(); } m_TcpClientPort = new KJTcpClientPort(socketArrayList, 1, iMark); m_TcpClientPort.DataReceived += new KJTcpClientPort.DataReceivedEventHandler(m_TcpClientPort_DataReceived); m_TcpClientPort.ErrorMessage += new SocketClient.ErrorMessageEventHandler(m_TcpClientPort_ErrorMessage); m_TcpClientPort.StationStateChanged += delegate(int index, int iAddress, int iState, string strStateRemark) { if (StationStateChanged != null) { StationStateChanged(index, iAddress, iState, strStateRemark); } }; m_TcpClientPort.MarkStateChanged += delegate(int index, int IsMark) { if (MarkStateChanged != null) { MarkStateChanged(index, IsMark); } }; }
/// <summary> /// 加载网络信息 /// </summary> /// <param name="strPath">网络文件保存的路径</param> /// <returns></returns> public bool TcpClientLoad(string strPath) { DataTable dtTcpClient = BuildTcpClientTable(); try { if (!File.Exists(strPath)) { //创建station.xml文件 FileStream fs = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter sw = new StreamWriter(fs); sw.WriteLine("<?xml version='1.0' standalone='yes'?>"); sw.WriteLine("<DocumentElement>"); sw.WriteLine("</DocumentElement>"); sw.Flush(); sw.Close(); sw.Dispose(); fs.Close(); fs.Dispose(); } } catch { } try { dtTcpClient.ReadXml(strPath); int iTcpClientCount = dtTcpClient.Rows.Count; socketPackets = new SocketPacket[iTcpClientCount]; for (int i = 0; i < iTcpClientCount; i++) { DataRow dr = dtTcpClient.Rows[i]; socketPackets[i] = new SocketPacket(); socketPackets[i].ID = int.Parse(dr["IPID"].ToString()); socketPackets[i].IpAddress = dr["IpAddress"].ToString(); socketPackets[i].ClientPort = int.Parse(dr["IpPort"].ToString()); } } catch { try { File.Delete(strPath); } catch { } return false; } finally { // 释放表格对象 dtTcpClient.Dispose(); } return true; }
/// <summary> /// 网络信息改变了 /// </summary> static void tcpClinetUpdateTime_NetInfoChange() { DataTable dtTcpServer = BuildTcpServers(); try { dtTcpServer.ReadXml(strTcpIpSavePath); int iTcpServerCount = dtTcpServer.Rows.Count; _socketPacket = new SocketPacket[iTcpServerCount]; for (int i = 0; i < iTcpServerCount; i++) { DataRow dr = dtTcpServer.Rows[i]; _socketPacket[i] = new SocketPacket(); _socketPacket[i].ID = int.Parse(dr["IPID"].ToString()); _socketPacket[i].IpAddress = dr["IpAddress"].ToString(); _socketPacket[i].ClientPort = int.Parse(dr["IpPort"].ToString()); } if (_commType) { _startTcp.NetChange(_socketPacket); } } catch { } finally { dtTcpServer.Dispose(); dtTcpServer = null; } }
public bool NetChange(SocketPacket[] socketPackets) { if (m_TcpClientPort == null) return false; if (socketPackets == null || socketPackets.Length <= 0) { if (socketArrayList != null && socketArrayList.Count > 0) { m_TcpClientPort.Clean(); return true; } } else { ArrayList arrayListTemp = new ArrayList(); ArrayList arrayListOld = m_TcpClientPort.SocketClientList; bool falg = false; if (arrayListOld != null) { for (int k = 0; k < socketPackets.Length; k++) { falg = false; for (int i = 0; i < arrayListOld.Count; i++) { SocketPacket socketTemp = (SocketPacket)arrayListOld[i]; if (socketPackets[k].IpAddress.Equals(socketTemp.IpAddress) && socketPackets[k].ClientPort.Equals(socketTemp.ClientPort))//数据存在 { falg = true; break; } } //在原来数据中没有找到,则添加 if (!falg) { m_TcpClientPort.Add(socketPackets[k].IpAddress, socketPackets[k].ClientPort); } } for (int i = 0; i < arrayListOld.Count; i++) { falg = false; SocketPacket socketTemp = (SocketPacket)arrayListOld[i]; for (int k = 0; k < socketPackets.Length; k++) { if (socketPackets[k].IpAddress.Equals(socketTemp.IpAddress) && socketPackets[k].ClientPort.Equals(socketTemp.ClientPort))//数据存在 { falg = true; break; } } if (!falg)//移除 { m_TcpClientPort.Remove(socketTemp.IpAddress, socketTemp.ClientPort); } } } else //如果原始的为空,则添加进去 { for (int i = 0; i < socketPackets.Length; i++) { m_TcpClientPort.Add(socketPackets[i].IpAddress, socketPackets[i].ClientPort); } } } return true; }
/// <summary> /// 加载网络配置信息 /// </summary> /// <param name="strPath"></param> /// <returns></returns> public static bool TcpServersLoad(string strPath) { DataTable dtTcpServer = BuildTcpServers(); strTcpIpSavePath = System.Windows.Forms.Application.StartupPath.ToString() + @"\" + strPath; bool falg; try { if (File.Exists(System.Windows.Forms.Application.StartupPath.ToString() + @"\" + strPath)) { dtTcpServer.ReadXml(System.Windows.Forms.Application.StartupPath.ToString() + @"\" + strPath); int iTcpServerCount = dtTcpServer.Rows.Count; _socketPacket = new SocketPacket[iTcpServerCount]; for (int i = 0; i < iTcpServerCount; i++) { DataRow dr = dtTcpServer.Rows[i]; _socketPacket[i] = new SocketPacket(); _socketPacket[i].ID = int.Parse(dr["ipID"].ToString()); _socketPacket[i].IpAddress = dr["IpAddress"].ToString(); _socketPacket[i].ClientPort = int.Parse(dr["IpPort"].ToString()); } } else { _socketPacket = new SocketPacket[0]; } falg = true; } catch { falg = false; } finally { dtTcpServer.Dispose(); dtTcpServer = null; } return falg; }
/// <summary> /// 初始化连接端口 /// </summary> /// <param name="socketPackets"></param> /// <returns></returns> private bool InitSocket(SocketPacket[] socketPackets) { if (socketPackets == null || socketPackets.Length <= 0) return false; for (int i = 0; i < socketPackets.Length; i++) { socketArrayList.Add(socketPackets[i]); } return true; }