예제 #1
0
        private void AcceptConnectCallback(IAsyncResult ar)
        {
            Listener = (Socket)ar.AsyncState;

            //acknowledge the connection
            Socket incomingSocket = null;

            try
            {
                incomingSocket = Listener.EndAccept(ar);
            }
            catch
            {
                ReportError?.Invoke("EndAccept failed on incoming connection", "");
            }

            //put the listener back to listening
            Listener.BeginAccept(new AsyncCallback(AcceptConnectCallback), Listener);

            if (incomingSocket == null)
            {
                return;
            }
            IPEndPoint ep = (IPEndPoint)incomingSocket.RemoteEndPoint;

            TConnection C = new TConnection();

            C.Setup(incomingSocket, ep.Address, ep.Port, ConnectionBufSize);

            if (AllConnections.ContainsKey(C.Address) == false)
            {
                AllConnections.Add(C.Address, C);
                AllConnectionsList.Add(C);
            }

            //Signal that a new connection has been created
            NewConnection?.Invoke(C);

            //configure the socket to receive incoming data and arm the data reception event
            try
            {
                C.ConnectionSocket.BeginReceive(C.IncomingData, 0, C.IncomingData.Length, 0, new AsyncCallback(ReadCallback), C.Address);
            }
            catch
            {
                ReportError?.Invoke("BeginReceive failed on new connection", C.Address);
            }
        }
예제 #2
0
        /// <summary>
        /// Disconnect a client and remove it form the client list
        /// </summary>
        /// <param name="name">Client name</param>
        public void RemoveConnection(string name)
        {
            if (!AllConnections.ContainsKey(name))
            {
                return;
            }

            TConnection Conn = AllConnections[name];

            AllConnectionsList.Remove(Conn);

            Conn.IncomingData = null;
            Conn.OutgoingData = null;

            AllConnections.Remove(name);
        }
예제 #3
0
        private void CleanupConnections(object sender)
        {
            for (int i = 0; i < AllConnectionsList.Count; i++)
            {
                var C = AllConnectionsList[i];
                if (C.ConnStats.HasTimedOut)
                {
                    if (C.ConnectionSocket.Connected)
                    {
                        C.ConnectionSocket.Disconnect(false);
                    }

                    AllConnectionsList.Remove(C);
                    AllConnections.Remove(C.Address);
                }
            }
        }
예제 #4
0
 private void ClearAllConnections()
 {
     AllConnections.Clear();
     AllConnectionsList.Clear();
 }