/// <summary> /// Обработчик посылки данных по соединению /// </summary> /// <param name="ar"></param> protected void OnSend(IAsyncResult ar) { // Retrieve the socket from the async client object. TcpConnectionInfo connectInfo = (TcpConnectionInfo)ar.AsyncState; try { Socket handler = connectInfo.socket; if (handler != null) { if (handler.Handle.ToInt32() < 0) { return; } if (!handler.Connected) { return; } // Complete sending the data to the remote device. int bytesSent = handler.EndSend(ar); } } catch (SocketException ex) { CloseConnection(connectInfo, ex.Message); } catch (Exception ex) { CloseConnection(connectInfo, ex.Message); } }
public bool IsConnectionIP(object connect, string aClientIP) { if (connect == null) { return(false); } if (!(connect is TcpConnectionInfo)) { return(false); } TcpConnectionInfo connectInfo = (TcpConnectionInfo)connect; if (connectInfo.socket == null) { return(false); } SocketAddress addr = connectInfo.socket.RemoteEndPoint.Serialize(); string connectIP = ""; for (int i = 0; i < addr.Size; ++i) { connectIP += addr[i].ToString() + "."; } if (connectIP.Length > 0) { connectIP.Remove(connectIP.Length - 1, 1); } return(connectIP.Equals(connect)); }
public string GetConnectionAddress(object connect) { if (connect == null) { return(""); } if (!(connect is TcpConnectionInfo)) { return(""); } TcpConnectionInfo connectInfo = (TcpConnectionInfo)connect; if (connectInfo.socket == null) { return(""); } string connectionAddress = connectInfo.socket.RemoteEndPoint.ToString(); int colonPos = connectionAddress.IndexOf(':'); if (colonPos >= 0) { connectionAddress = connectionAddress.Substring(0, colonPos); } return(connectionAddress); }
public ushort GetConnectPort(object connect) { if (connect == null) { return(0); } if (!(connect is TcpConnectionInfo)) { return(0); } TcpConnectionInfo connectInfo = (TcpConnectionInfo)connect; if (connectInfo.socket == null) { return(0); } string connectionAddress = connectInfo.socket.RemoteEndPoint.ToString(); int colonPos = connectionAddress.IndexOf(':'); if (colonPos >= 0) { connectionAddress = connectionAddress.Substring(colonPos + 1, connectionAddress.Length - colonPos - 1); } try { return(UInt16.Parse(connectionAddress)); } catch (System.Exception e) { return(0); } }
public override void CloseConnection(IConnectionInfo connect, string sMsg) { TcpConnectionInfo connectInfo = (TcpConnectionInfo)connect; if (connectInfo != null && connectInfo.socket != null) { try { if (connectInfo.socket.Handle.ToInt32() >= 0 && connectInfo.socket.Connected) { connectInfo.socket.Shutdown(SocketShutdown.Both); } connectInfo.socket.Close(); connectInfo.socket = null; connectInfo.session = null; connectInfo = null; } catch (Exception exc) { try { connectInfo.socket.Close(); } catch (Exception exc1) { } if (connectInfo != null) { connectInfo.socket = null; connectInfo.session = null; } connectInfo = null; } } }
/// <summary> /// Закрывает соединение /// </summary> /// <param name="connect"></param> public override void CloseConnection(IConnectionInfo connect, string sMsg) { try { if (connect == null) { return; } TcpConnectionInfo connectInfo = null; if (connect is TcpConnectionInfo) { connectInfo = (TcpConnectionInfo)connect; } if (connectInfo == null) { return; } if (connectInfo.isClosing) { lock (connections) { connections.Remove(connectInfo); } return; } connectInfo.isClosing = true; if (sessionFactory != null && connectInfo.session != null) { sessionFactory.DestroySession(connectInfo.session); } if (connectInfo.session != null && !connectInfo.session.IsClosed()) { connectInfo.session.CloseHandlers(); } if (connectInfo.socket != null) { connectInfo.socket.Close(); connectInfo.socket = null; } lock (connections) { connections.Remove(connectInfo); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при закрытии соединения"); } }
/// <summary> /// Посылает данные клиенту /// </summary> /// <param name="connect">Содинение</param> /// <param name="data">Массив с данными</param> public override void Send(IConnectionInfo connect, byte[] data, uint size) { if (size == 0) { return; } if (connect == null) { return; } bool needClose = false; if (!(connect is TcpConnectionInfo)) { return; } TcpConnectionInfo connectInfo = (TcpConnectionInfo)connect; if (connectInfo.socket != null) { if (connectInfo.socket.Handle.ToInt32() < 0) { return; } if (!connectInfo.socket.Connected) { needClose = true; } else { try { connectInfo.socket.BeginSend(data, 0, (int)size, 0, new AsyncCallback(OnSend), connectInfo); } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка отправки данных"); } } } if (needClose) { CloseConnection(connectInfo, ""); } }
/// <summary> /// Обработчик получения данных по соединению /// </summary> /// <param name="ar">Параметры получения данных</param> protected void OnReceive(IAsyncResult ar) { // Ссылка на соединение TcpConnectionInfo connect = null; try { connect = (TcpConnectionInfo)ar.AsyncState; if (connect == null) { return; } // Завершаем операцию получения данных int readBytes = 0; if (connect.socket != null && connect.socket.Handle.ToInt32() >= 0) { readBytes = connect.socket.EndReceive(ar); } if (readBytes <= 0) { CloseConnection(connect, ""); } // Обрабатывает полученные данные if (connect.session == null) { return; } if (connect.session.IsClosed()) { return; } connect.session.ReceiveData(connect.buffer, readBytes); connect.socket.BeginReceive(connect.buffer, 0, connect.buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), connect); } catch (SocketException exc) { CloseConnection(connect, exc.Message); } catch (Exception exc) { CloseConnection(connect, exc.Message); } }
/// <summary> /// Обработчик запроса на соединение /// </summary> /// <param name="ar">Параметры запроса на соединение</param> protected void OnAccept(IAsyncResult ar) { if (socketListener == null) { return; } if (socketListener.Handle.ToInt32() < 0) { return; } // Создаем соединение TcpConnectionInfo connect = new TcpConnectionInfo(); try { // Завершаем операцию Accept и доопределяем описатель соединения Socket s = (Socket)ar.AsyncState; if (s.Handle.ToInt32() < 0) { return; } connect.socket = s.EndAccept(ar); if (maxConnectionNumber > 0 && connections.Count >= maxConnectionNumber) { connect.socket.Close(); connect.socket = null; return; } connect.buffer = new byte[1024]; // Создаем соединение if (sessionFactory != null) { connect.session = sessionFactory.CreateSession(this, connect); lock (connections) { connections.Add(connect); } // асинхронно if (connect.socket != null) { AsyncCallback receiver = new AsyncCallback(OnReceive); connect.socket.BeginReceive(connect.buffer, 0, connect.buffer.Length, SocketFlags.None, receiver, connect); } } } catch (SocketException exc) { CloseConnection(connect, ""); } catch (Exception exc) { CloseConnection(connect, ""); } // Начинаем асинхронную новую операцию Accept if (socketListener == null) { return; } socketListener.BeginAccept(new AsyncCallback(OnAccept), socketListener); }
protected void DisConnectImpl() { bTerminating = true; CloseConnection(connectInfo, ""); connectInfo = null; }
public TcpClient() { socket = null; connectInfo = null; session = null; }