Пример #1
0
        private async Task DataReceiver(ElyClient tcpC)
        {
            try
            {
                byte[] inValue = new byte[] { 1, 0, 0, 0, 0x10, 0x27, 0, 0, 0xe8, 0x03, 0, 0 };//{1,10000ms,1000ms}
                tcpC.TcpHandle.Client.IOControl(IOControlCode.KeepAliveValues, inValue, null);
                // 循环监听&接收数据
                while (!Token.IsCancellationRequested)
                {
                    byte[] data = await MessageReadAsync(tcpC);

                    if (data != null && iDataReceivedFDback != null)
                    {
                        Task <bool> unwaited = Task.Run(() => iDataReceivedFDback(tcpC.IpPortStr, data));
                    }
                }
            }
            finally
            {
                RemoveClient(tcpC);
                if (iDisconnectedFDback != null)
                {
                    Task <bool> unwaited = Task.Run(() => iDisconnectedFDback(tcpC.IpPortStr));
                }
                tcpC.Dispose();
            }
        }
Пример #2
0
        private async Task AccecptConnection()
        {
            while (!Token.IsCancellationRequested)
            {
                try
                {
                    if (CurrentClientNum >= MaxClientNum)
                    {
                        await Task.Delay(100);

                        continue;
                    }

                    TcpClient tcpClient = await iTcpListener.AcceptTcpClientAsync();

                    ElyClient tcpC   = new ElyClient(tcpClient);
                    Task      unwait = Task.Run(() => HandleConnectedClient(tcpC), Token);
                }
                catch (SocketException)
                {
                    break;
                }
            }
            this.Dispose();
        }
Пример #3
0
        private async Task <byte[]> MessageReadAsync(ElyClient client)
        {
            byte[] contentBytes = null;

            if (!client.Sstream.CanRead)
            {
                return(null);
            }

            #region Read-Data
            using (MemoryStream dataMs = new MemoryStream())
            {
                int    recvd      = 0;
                int    bufferSize = 2048;
                byte[] buffer     = new byte[bufferSize];
                if ((recvd = await client.Sstream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    dataMs.Write(buffer, 0, recvd);
                }
                if (dataMs.Length > 0)
                {
                    contentBytes = dataMs.ToArray();
                }
                else if (recvd == 0)  //Reach EOF
                {
                    throw new SocketException();
                }
            }
            #endregion
            return(contentBytes);
        }
Пример #4
0
 private void AddClient(ElyClient tcpC)
 {
     if (ClientList != null)
     {
         ClientList.TryAdd(tcpC.IpPortStr, tcpC);
         Interlocked.Increment(ref CurrentClientNum);
     }
 }
Пример #5
0
 private void RemoveClient(ElyClient tcpC)
 {
     if (ClientList != null)
     {
         ElyClient RmClient = null;
         ClientList.TryRemove(tcpC.IpPortStr, out RmClient);
         Interlocked.Decrement(ref CurrentClientNum);
     }
 }
Пример #6
0
 private void HandleConnectedClient(ElyClient tcpC)
 {
     AddClient(tcpC);
     if (iConnectedFDback != null)
     {
         Task <bool> unwaited = Task.Run(() => iConnectedFDback(tcpC.IpPortStr));
     }
     Task.Run(() => DataReceiver(tcpC), Token);
 }
Пример #7
0
        public void Disconnect(string IpPort)
        {
            ElyClient ElyC = null;

            if (ClientList.TryGetValue(IpPort, out ElyC))
            {
                RemoveClient(ElyC);
                ElyC.Dispose();
            }
        }
Пример #8
0
        // Send/disconnect/is connected
        public async Task <bool> Send(string IpPort, byte[] data)
        {
            ElyClient ElyC = null;

            if (ClientList.TryGetValue(IpPort, out ElyC))
            {
                return(await MessageWriteAsync(ElyC, data));
            }
            else
            {
                throw new ArgumentNullException();
            }
        }
Пример #9
0
        private async Task <bool> MessageWriteAsync(ElyClient ElyC, byte[] data)
        {
            try
            {
                if (ElyC.TcpHandle.Client.Poll(2 * 1000 * 1000, SelectMode.SelectWrite))
                {
                    await ElyC.Nstream.WriteAsync(data, 0, data.Length);

                    await ElyC.Nstream.FlushAsync();

                    return(true);
                }
                return(false);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Пример #10
0
        private async Task <bool> StartSslConnection(ElyClient sslC)
        {
            try
            {
                SslProtocols SSLVer = GetUserSetProtocalType();
                await sslC.Sstream.AuthenticateAsServerAsync(SslCertificate, iMaumutually, SSLVer, false);

                if (!sslC.Sstream.IsEncrypted)
                {
                    throw new Exception("此连接未进行加密处理");
                }
                if (!sslC.Sstream.IsAuthenticated)
                {
                    throw new Exception("身份验证失败");
                }
                if (iMaumutually && !sslC.Sstream.IsMutuallyAuthenticated)
                {
                    throw new Exception("客户端证书验证失败");
                }
                // SSL证书验证成功,加入客户端列表,监听数据
                HandleConnectedClient(sslC);
                return(true);
            }
            catch (Exception ex)
            {
                Task unwait = null;
                if (ex.InnerException != null)
                {
                    unwait = Task.Run(() => iPromptMsgPrinter($"Error: [{sslC.IpPortStr}] {ex.InnerException.Message}"));
                }
                else
                {
                    unwait = Task.Run(() => iPromptMsgPrinter($"Error: [{sslC.IpPortStr}] {ex.Message}"));
                }

                sslC.Dispose();
                return(false);
            }
        }
Пример #11
0
        private async Task <byte[]> MessageReadAsync(ElyClient client)
        {
            byte[] ContentBytes = null;
            if (!client.Nstream.CanRead)
            {
                return(null);
            }

            #region Read-Data
            using (MemoryStream dataMs = new MemoryStream())
            {
                int    recvd      = 0;
                int    bufferSize = 2048;
                byte[] buffer     = new byte[bufferSize];
                //Caller 捕获此函数的异常
                while ((recvd = await client.Nstream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    dataMs.Write(buffer, 0, recvd);
                    if (!client.Nstream.DataAvailable)
                    {
                        break;
                    }
                }
                //若对端断开了连接,但接收到了一些数据,总是先上报,下次循环再断开连接
                if (dataMs.Length > 0)
                {
                    ContentBytes = dataMs.ToArray();
                }
                else if (recvd == 0)
                {
                    throw new SocketException();
                }
            }
            #endregion
            return(ContentBytes);
        }
Пример #12
0
        private async Task AccecptConnection()
        {
            while (!Token.IsCancellationRequested)
            {
                try
                {
                    if (CurrentClientNum >= MaxClientNum)
                    {
                        await Task.Delay(100);

                        continue;
                    }
                    #region accept-connection
                    TcpClient tcpClient = await iTcpListener.AcceptTcpClientAsync();

                    #endregion

                    var sslClient = new ElyClient(tcpClient);
                    if (iAcceptInvalidCert)
                    {
                        sslClient.Sstream = new SslStream(sslClient.Nstream, false, new RemoteCertificateValidationCallback(AcceptInvalidCert));
                    }
                    else
                    {
                        sslClient.Sstream = new SslStream(sslClient.Nstream, false);
                    }
                    sslClient.IpPortStr = sslClient.IpPortStr.Replace("TCP", "TLS");
                    Task unwait = Task.Run(() => StartSslConnection(sslClient), Token);
                }
                catch (SocketException)
                {
                    break;
                }
            }
            this.Dispose();
        }