/// <summary> /// 开始连接远程服务器 /// </summary> /// <param name="SocketPacketRB">要连接的远程服务器包</param> private void StartClient(SocketPacketRB 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 (Exception e) { try { if (socketPacket.State == 1 && socketPacket.ErrorShow == false) { tA.Stop(); ErrorMessage(8033002, e.StackTrace, "[Base_SocketClient:StartClient]", socketPacket.IpAddress + "未连接"); socketPacket.ErrorShow = true; } socketPacket.State = 2; } catch { } } }
/// <summary> /// 等待从客户端发送过来的数据 /// </summary> /// <param name="soc"></param> /// <param name="clientNumber"></param> public void WaitForData(SocketPacketRB soc) { try { if (pfnWorkerCallBack == null) { // 获取等待发送数据回调方法 pfnWorkerCallBack = new AsyncCallback(OnDataReceived); } soc.DataBuffer = new byte[soc.DataLength]; //调用开始异步接收数据方法 soc.CurrentSocket.BeginReceive(soc.DataBuffer, 0, soc.DataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, soc); } catch (Exception se) { if (soc != null && soc.CurrentSocket != null) { if (ClientConnect != null) { ClientConnect(((IPEndPoint)soc.CurrentSocket.RemoteEndPoint).Address.ToString(), false); } } if (ErrorMessage != null && soc.ErrorShow == false) { soc.ErrorShow = false; ErrorMessage(8033002, se.StackTrace, "[Base_SocketClient:StartClient]", se.Message); } } }
/// <summary> /// 添加远程连接 /// </summary> /// <param name="strIpAddress">远程连接地址</param> /// <param name="port">远程连接端口</param> public void Add(string strIpAddress, int port) { #region [判断要连接的列表中是否存在] SocketPacketRB spCollect; for (int i = 0; i < m_socketClientList.Count; i++) { spCollect = (SocketPacketRB)m_socketClientList[i]; if (spCollect.IpAddress.Equals(strIpAddress) && spCollect.ClientPort.Equals(port)) { return; } } spCollect = null; #endregion [判断要连接的列表中是否存在] #region [添加到要连接的服务器列表中] SocketPacketRB sp = new SocketPacketRB(); sp.IpAddress = strIpAddress; sp.ClientPort = port; sp.ErrorShow = false; sp.State = 0; m_socketClientList.Add(sp); #endregion [添加到要连接的服务器列表中] //开始连接远程服务器 StartClient(sp); }
/// <summary> /// 重新连接远程主机 /// </summary> private void Repeat() { while (true) { try { for (int i = 0; i < m_socketClientList.Count; i++) { SocketPacketRB s = (SocketPacketRB)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="socketPacket">远程连接对象包</param> private void WaitForData(SocketPacketRB 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 (Exception se) { try { if ((socketPacket.State == 0 || socketPacket.State == 2) && socketPacket.ErrorShow == false) { tA.Stop(); ErrorMessage(8033002, se.StackTrace, "[Base_SocketClient:WaitForData]", socketPacket.IpAddress + "未连接"); socketPacket.ErrorShow = true; } if (socketPacket.CurrentSocket != null) { socketPacket.CurrentSocket.Close(); socketPacket.CurrentSocket = null; } } catch { } } }
/// <summary> /// 结束挂起的异步发送 /// </summary> /// <param name="ar">异步操作对象</param> private void SendCallback(IAsyncResult ar) { SocketPacketRB sp_SendCallbace = new SocketPacketRB(); try { sp_SendCallbace = (SocketPacketRB)ar.AsyncState; sp_SendCallbace.CurrentSocket.EndSend(ar); } catch (Exception e) { try { if (sp_SendCallbace.State == 2 && !sp_SendCallbace.IpAddress.Equals("") && sp_SendCallbace.ErrorShow == false) { tA.Stop(); ErrorMessage(8033002, e.StackTrace, "[Base_SocketClient:SendCallback]", sp_SendCallbace.IpAddress + "未连接"); sp_SendCallbace.ErrorShow = true; } if (sp_SendCallbace.CurrentSocket != null) { sp_SendCallbace.CurrentSocket.Close(); sp_SendCallbace.CurrentSocket = null; } } catch { } } }
/// <summary> /// 结束挂起的等待接收数据线程 /// </summary> /// <param name="asyn">异步调用对象</param> private void OnDataReceived(IAsyncResult asyn) { SocketPacketRB socketPacket_Received = null; try { socketPacket_Received = (SocketPacketRB)asyn.AsyncState; int iRx = socketPacket_Received.CurrentSocket.EndReceive(asyn); //获取异步读取得到的数据包 char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(socketPacket_Received.DataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); //// 获取得到的字符 //byte[] bytes = new byte[iRx]; //for (int i = 0; i < iRx; i++) //{ // bytes[i] = socketPacket_Received.DataBuffer[i]; //} if (DataReceivedByAddress != null) { //调用数据获取事件 DataReceivedByAddress(szData, socketPacket_Received.IpAddress); } } catch (Exception se) { try { if ((socketPacket_Received.State == 0 || socketPacket_Received.State == 2) && socketPacket_Received.ErrorShow == false) { tA.Stop(); ErrorMessage(8033002, se.StackTrace, "[Base_SocketClient:WaitForData]", socketPacket_Received.IpAddress + "未连接"); socketPacket_Received.ErrorShow = true; } if (socketPacket_Received.CurrentSocket != null) { socketPacket_Received.CurrentSocket.Close(); socketPacket_Received.CurrentSocket = null; } } catch { } } finally { if (socketPacket_Received != null) { tA.Start(); //继续等待数据 WaitForData(socketPacket_Received); } } }
void tA_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { tA.Stop(); for (int i = 0; i < m_socketClientList.Count; i++) { SocketPacketRB s = (SocketPacketRB)m_socketClientList[i]; byte[] byData = System.Text.Encoding.ASCII.GetBytes("1"); Send(byData, s.IpAddress, s.ClientPort); } tA.Start(); }
/// <summary> /// 回调方法 客户端请求连接同意 /// </summary> /// <param name="asyn"></param> public void OnClientConnect(IAsyncResult asyn) { Socket workerSocket = null; SocketPacketRB sp = null; try { //同意接收接入 workerSocket = m_mainSocket.EndAccept(asyn); sp = new SocketPacketRB(); sp.ErrorShow = false; sp.CurrentSocket = workerSocket; sp.IpAddress = ((IPEndPoint)workerSocket.RemoteEndPoint).Address.ToString(); // 把接入的Socket添加到动态数组中 m_workerSocketList.Add(sp); if (ClientConnect != null) { ClientConnect(((IPEndPoint)workerSocket.RemoteEndPoint).Address.ToString(), true); } } catch (Exception ee) { if (workerSocket != null) { if (ClientConnect != null) { ClientConnect(((IPEndPoint)workerSocket.RemoteEndPoint).Address.ToString(), false); } } if (ErrorMessage != null && sp.ErrorShow == false) { sp.ErrorShow = true; ErrorMessage(8033002, ee.StackTrace, "[Base_SocketClient:StartClient]", ee.Message); } } finally { if (sp != null) { if (sp.CurrentSocket != null && sp.CurrentSocket.Connected) { //ErrorMessage(30007, "", "[Base_SocketClient:ConnectCallback]", SocketPacketRB.IpAddress + "已连接"); sp.ErrorShow = false; //等待接收数据 WaitForData(sp); //其他客户端连接,异步调用请求同意方法 m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null); } } } }
/// <summary> /// 开始发送数据 /// </summary> /// <param name="bytes">发送字节</param> /// <param name="strIpAddress">发送的地址</param> /// <param name="port">发送的端口</param> public void Send(byte[] bytes, string strIpAddress) { SocketPacketRB spCollect = new SocketPacketRB(); try { for (int i = 0; i < m_workerSocketList.Count; i++) { spCollect = (SocketPacketRB)m_workerSocketList[i]; if (spCollect.IpAddress.Equals(strIpAddress)) { //开始异步发送数据 spCollect.CurrentSocket.BeginSend(bytes, 0, bytes.Length, 0, new AsyncCallback(SendCallback), spCollect); break; } } } catch (SocketException se) { try { if (spCollect != null && spCollect.CurrentSocket != null) { if (ClientConnect != null) { ClientConnect(((IPEndPoint)spCollect.CurrentSocket.RemoteEndPoint).Address.ToString(), false); } } if (!spCollect.IpAddress.Equals("") && spCollect.ErrorShow == false) { ErrorMessage(8033002, se.StackTrace, "[Base_SocketClient:Send]", spCollect.IpAddress + "未连接"); spCollect.ErrorShow = true; } if (spCollect.CurrentSocket != null) { spCollect.CurrentSocket.Close(); spCollect.CurrentSocket = null; } } catch { } } catch (Exception ee) { } }
/// <summary> /// 构造客户端连接对象 /// </summary> /// <param name="socketArrayList">客户端连接列表</param> public ClientRB(string strIPaddress, int port) { if (baseSocketClient == null) { ArrayList socketArrayList = new ArrayList(); socketPack = new SocketPacketRB(); socketPack.IpAddress = strIPaddress; socketPack.ClientPort = port; socketPack.ErrorShow = false; socketPack.State = 0; socketArrayList.Add(socketPack); //创建链接服务器 rbSqlConn.ExecCreadLineServer(strIPaddress); baseSocketClient = new SocketClient(socketArrayList); baseSocketClient.DataReceivedByAddress += new SocketClient.DataReceivedEventHandler(baseSocketClient_DataReceivedByAddress); baseSocketClient.ErrorMessage += new SocketClient.ErrorMessageEventHandler(baseSocketClient_ErrorMessage); //开始连接远程服务器 RepeatStart(); } }
/// <summary> /// 结束挂起的连接请求 /// </summary> /// <param name="ar">异步调用对象</param> private void ConnectCallback(IAsyncResult ar) { //获取异步操作对象 SocketPacketRB socketPacket = (SocketPacketRB)ar.AsyncState; try { // 与远程主机连接完成 socketPacket.CurrentSocket.EndConnect(ar); } catch (Exception e) { try { if (socketPacket.State == 1 && socketPacket.ErrorShow == false) { tA.Stop(); ErrorMessage(8033002, e.StackTrace, "[Base_SocketClient:ConnectCallback]", socketPacket.IpAddress + "未连接"); socketPacket.ErrorShow = true; } } catch { } } finally { if (socketPacket != null) { socketPacket.State = 2; if (socketPacket.CurrentSocket != null && socketPacket.CurrentSocket.Connected) { ErrorMessage(8033001, "", "[Base_SocketClient:ConnectCallback]", socketPacket.IpAddress + "已连接"); socketPacket.ErrorShow = false; tA.Start(); //等待接收数据 WaitForData(socketPacket); } } } }
/// <summary> /// 结束挂起的异步发送 /// </summary> /// <param name="ar">异步操作对象</param> private void SendCallback(IAsyncResult ar) { SocketPacketRB sp_SendCallbace = new SocketPacketRB(); try { sp_SendCallbace = (SocketPacketRB)ar.AsyncState; sp_SendCallbace.CurrentSocket.EndSend(ar); } catch (SocketException e) { try { if (sp_SendCallbace != null && sp_SendCallbace.CurrentSocket != null) { if (ClientConnect != null) { ClientConnect(((IPEndPoint)sp_SendCallbace.CurrentSocket.RemoteEndPoint).Address.ToString(), false); } } if (sp_SendCallbace.State == 2 && !sp_SendCallbace.IpAddress.Equals("") && sp_SendCallbace.ErrorShow == false) { ErrorMessage(8033002, e.StackTrace, "[Base_SocketClient:SendCallback]", sp_SendCallbace.IpAddress + "未连接"); sp_SendCallbace.ErrorShow = true; } if (sp_SendCallbace.CurrentSocket != null) { sp_SendCallbace.CurrentSocket.Close(); sp_SendCallbace.CurrentSocket = null; } } catch { } } catch (Exception ee) { } }
/// <summary> /// 开始发送数据 /// </summary> /// <param name="bytes">发送字节</param> /// <param name="strIpAddress">发送的地址</param> /// <param name="port">发送的端口</param> public void Send(byte[] bytes, string strIpAddress, int port) { SocketPacketRB spCollect = new SocketPacketRB(); try { for (int i = 0; i < m_socketClientList.Count; i++) { spCollect = (SocketPacketRB)m_socketClientList[i]; if (spCollect.IpAddress.Equals(strIpAddress) && spCollect.ClientPort.Equals(port)) { //开始异步发送数据 spCollect.CurrentSocket.BeginSend(bytes, 0, bytes.Length, 0, new AsyncCallback(SendCallback), spCollect); break; } } } catch (Exception ee) { try { if (spCollect.State == 2 && !spCollect.IpAddress.Equals("") && spCollect.ErrorShow == false) { tA.Stop(); ErrorMessage(8033002, ee.StackTrace, "[Base_SocketClient:Send]", spCollect.IpAddress + "未连接"); spCollect.ErrorShow = true; } if (spCollect.CurrentSocket != null) { spCollect.CurrentSocket.Close(); spCollect.CurrentSocket = null; } } catch { } } }
/// <summary> /// 等待从客户端发送过来的数据 /// </summary> /// <param name="soc"></param> /// <param name="clientNumber"></param> public void WaitForData(SocketPacketRB soc) { try { if (pfnWorkerCallBack == null) { // 获取等待发送数据回调方法 pfnWorkerCallBack = new AsyncCallback(OnDataReceived); } soc.DataBuffer = new byte[soc.DataLength]; //调用开始异步接收数据方法 soc.CurrentSocket.BeginReceive(soc.DataBuffer, 0, soc.DataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, soc); } catch (Exception se) { if (soc != null && soc.CurrentSocket!=null) { if (ClientConnect != null) { ClientConnect(((IPEndPoint)soc.CurrentSocket.RemoteEndPoint).Address.ToString(), false); } } if (ErrorMessage != null && soc.ErrorShow == false) { soc.ErrorShow = false; ErrorMessage(8033002, se.StackTrace, "[Base_SocketClient:StartClient]", se.Message); } } }
/// <summary> /// 回调方法 客户端请求连接同意 /// </summary> /// <param name="asyn"></param> public void OnClientConnect(IAsyncResult asyn) { Socket workerSocket = null; SocketPacketRB sp = null; try { //同意接收接入 workerSocket = m_mainSocket.EndAccept(asyn); sp = new SocketPacketRB(); sp.ErrorShow = false; sp.CurrentSocket = workerSocket; sp.IpAddress = ((IPEndPoint)workerSocket.RemoteEndPoint).Address.ToString(); // 把接入的Socket添加到动态数组中 m_workerSocketList.Add(sp); if (ClientConnect != null) { ClientConnect(((IPEndPoint)workerSocket.RemoteEndPoint).Address.ToString(), true); } } catch(Exception ee) { if (workerSocket != null) { if (ClientConnect != null) { ClientConnect(((IPEndPoint)workerSocket.RemoteEndPoint).Address.ToString(), false); } } if (ErrorMessage != null && sp.ErrorShow == false) { sp.ErrorShow = true; ErrorMessage(8033002, ee.StackTrace, "[Base_SocketClient:StartClient]", ee.Message); } } finally { if (sp != null) { if (sp.CurrentSocket != null && sp.CurrentSocket.Connected) { //ErrorMessage(30007, "", "[Base_SocketClient:ConnectCallback]", SocketPacketRB.IpAddress + "已连接"); sp.ErrorShow = false; //等待接收数据 WaitForData(sp); //其他客户端连接,异步调用请求同意方法 m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null); } } } }
/// <summary> /// 接收数据方法 /// </summary> /// <param name="asyn"></param> public void OnDataReceived(IAsyncResult asyn) { SocketPacketRB socketData = null; try { socketData = (SocketPacketRB)asyn.AsyncState; //获取异步读取得到的数据包 int iRx = socketData.CurrentSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(socketData.DataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); if (DataReceivedByAddress != null) { DataReceivedByAddress(szData, ((IPEndPoint)socketData.CurrentSocket.RemoteEndPoint).Address.ToString()); ////Czlt-2012-2-24 //if (ErrorMessage != null) //{ // ErrorMessage(8033001, "", "[Base_SocketClient:StartClient]", "已连接"); //} } } catch (SocketException se) { if (se.ErrorCode == 10054 && socketData.ErrorShow == false) { socketData.ErrorShow = true; //移除 if (socketData.CurrentSocket != null) { socketData.CurrentSocket.Close(); socketData.CurrentSocket = null; } m_workerSocketList.Remove(socketData); //m_workerSocketList[socketData.m_clientNumber - 1] = null; if (socketData != null && socketData.CurrentSocket != null) { if (ClientConnect != null) { ClientConnect(((IPEndPoint)socketData.CurrentSocket.RemoteEndPoint).Address.ToString(), false); } } try { if (ErrorMessage != null) { ErrorMessage(8033002, se.StackTrace, "[Base_SocketClient:StartClient]", se.Message); } } catch { } } } finally { if (socketData != null && socketData.CurrentSocket != null) { //继续等待数据 WaitForData(socketData); } } }