Exemple #1
0
        private static async Task OneDataReceiver(OneMetadata md)
        {
            var header = "[" + md.TcpClient.Client.RemoteEndPoint.ToString() + "]";

            try
            {
                while (true)
                {
                    if (!IsClientConnected(md.TcpClient))
                    {
                        if (isDebug)
                        {
                            Logger.Warn(header + " client no longer connected");
                        }
                        break;
                    }

                    if (Token.IsCancellationRequested)
                    {
                        if (isDebug)
                        {
                            Logger.Warn(header + " cancellation requested");
                        }

                        break;
                    }

                    var data = await DataReadAsync(md.TcpClient, Token);

                    if (data == null || data.Length < 1)
                    {
                        Thread.Sleep(10);
                        continue;
                    }

                    var length = data.Length;

                    var crc32 = data.Take(length - 2).ToArray().CRC16();
                    if (data[length - 2] == crc32[1] && data[length - 1] == crc32[0])
                    {
                        ManyQueue.Enqueue(data.Take(data.Length).ToArray());
                    }
                }
            }
            catch (Exception e)
            {
                $"one client excetion {e.Message}, {e.StackTrace}".Error();
            }
            OneClients.TryRemove(md.TcpClient.Client.RemoteEndPoint.ToString(), out _);
            md.Dispose();
        }
Exemple #2
0
        private static async Task OneAcceptConnections(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                try
                {
                    var client = await OneListener.AcceptTcpClientAsync();

                    var md = new OneMetadata(client);

                    $"One客户端已连接,IP:{client.Client.RemoteEndPoint}".Info();

                    OneClients.TryAdd(client.Client.RemoteEndPoint.ToString(), md);
                    await Task.Run(() => OneDataReceiver(md), md.Token);
                }
                catch (Exception e)
                {
                    Logger.Error(e);
                    throw;
                }
            }
        }