Пример #1
0
        public async Task <IActionResult> List()
        {
            if (!await _client.ConnectAsync(new IPEndPoint(_address, _serverPort)))
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, "Failed to connect to the server."));
            }

            await _client.SendAsync(Encoding.UTF8.GetBytes($"{CommandKey.Connect} {ClientType.Short.ToString()}{Package.Terminator}"));

            while (true)
            {
                var p = await _client.ReceiveAsync();

                if (p == null)
                {
                    return(StatusCode((int)HttpStatusCode.InternalServerError, "Connection dropped."));
                }

                switch (p.Key)
                {
                case CommandKey.Connected:
                    await _client.SendAsync(Encoding.UTF8.GetBytes($"{CommandKey.ListClient}{Package.Terminator}"));

                    break;

                default:
                    var clients = JsonConvert.DeserializeObject <List <ClientInfo> >(p.Content).OrderByDescending(n => n.ConnectTime);
                    await _client.CloseAsync();

                    return(Ok(clients));
                }
            }
        }
        public override async ValueTask <FastDFSResp> SendRequestAsync <T>(FastDFSReq <T> request)
        {
            _tcs = new TaskCompletionSource <FastDFSResp>();

            _resp = new T();

            //上下文,当前的信息
            _context = BuildContext <T>(request);

            var bodyBuffer = request.EncodeBody(Configuration);

            if (request.Header.Length == 0)
            {
                request.Header.Length = request.InputStream != null ? request.InputStream.Length + bodyBuffer.Length : bodyBuffer.Length;
            }

            var headerBuffer = request.Header.ToBytes();
            var newBuffer    = ByteUtil.Combine(headerBuffer, bodyBuffer);

            //流文件发送
            if (request.InputStream != null)
            {
                await _client.SendAsync(newBuffer);

                using (request.InputStream)
                {
                    var chunkSize = 8192;

                    while (true)
                    {
                        var availableBytes = request.InputStream.Length - request.InputStream.Position;
                        if (availableBytes <= 0)
                        {
                            break;
                        }

                        int readChunkSize = (int)Math.Min(chunkSize, availableBytes);

                        var buffers = new byte[readChunkSize];
                        _ = await request.InputStream.ReadAsync(buffers, 0, buffers.Length);

                        await _client.SendAsync(buffers);
                    }
                }
            }
            else
            {
                await _client.SendAsync(newBuffer);
            }

            return(await _tcs.Task);
        }
        private async Task SendMessage(string message)
        {
            var sendPackage = new TcpPackage()
            {
                OpCode      = LbChatWith.Content.Equals("All") ? OpCode.All : OpCode.Single,
                MessageType = MessageType.Text,
                LocalName   = TbUserName.Text,
                RemoteName  = LbChatWith.Content.ToString(),
                Message     = message
            };

            ChatArea.Children.Add(new SendControl(sendPackage, null));
            var msg = sendPackage.ToString();
            await _sendTcpClient.SendAsync(new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(msg)));

            Scr.ScrollToEnd();
        }
Пример #4
0
        private async ValueTask SendAllRequestsInQueue(IEasyClient <Response, Request> client, int index)
        {
            if (!_uncheckedRequests.TryGetValue((EasyClient <Response>)client, out var uncheckedRequest))
            {
                return;
            }
            var success = false;

            while (!success)
            {
                success = await Connect(index);

                if (!success)
                {
                    Thread.Sleep(1000);
                }
            }
            while (_running)
            {
                if (_uncheckedRequests.Count > MaxSizeOfUncheckedRequestList)
                {
                    Thread.Sleep(100);
                    continue;
                }
                var request = await _toBeSendRequests.Dequeue();

                // 若请求已超时,则放弃
                if (request.IsTimeout)
                {
                    continue;
                }
                try
                {
                    await client.SendAsync(request.Request);

                    uncheckedRequest.Add(new Tuple <DateTime, RequestWithTimeout>(DateTime.Now, request));
                }
                catch
                {
                    if (!_running)
                    {
                        return;
                    }
                    await _toBeSendRequests.Enqueue(request,
                                                    new RequestPriority(0, request.Request.Id));

                    success = await Connect(index);

                    if (!success)
                    {
                        Thread.Sleep(200);
                    }
                }
            }
        }
Пример #5
0
        public override Task <FastDFSResp> SendRequestAsync <T>(FastDFSReq <T> request)
        {
            _taskCompletionSource = new TaskCompletionSource <FastDFSResp>();
            //上下文,当前的信息
            _context = BuildContext <T>(request);

            var bodyBuffer = request.EncodeBody(Option);

            if (request.Header.Length == 0)
            {
                request.Header.Length = request.InputStream != null ? request.InputStream.Length + bodyBuffer.Length : bodyBuffer.Length;
            }

            var headerBuffer = request.Header.ToBytes();
            var newBuffer    = ByteUtil.Combine(headerBuffer, bodyBuffer);

            //流文件发送
            if (request.InputStream != null)
            {
                _client.SendAsync(newBuffer);

                using (request.InputStream)
                {
                    //设置缓冲区大小
                    byte[] buffers = new byte[1024 * 1024];
                    //读取一次
                    int r = request.InputStream.Read(buffers, 0, buffers.Length);
                    //判断本次是否读取到了数据
                    while (r > 0)
                    {
                        _client.SendAsync(buffers).AsTask().Wait();
                        r = request.InputStream.Read(buffers, 0, buffers.Length);
                    }
                }
            }
            else
            {
                _client.SendAsync(newBuffer).AsTask().Wait();
            }
            return(_taskCompletionSource.Task);
        }
Пример #6
0
        static async Task Main(string[] args)
        {
            client = new EasyClient <TextPackageInfo>(new MyPackageFilter()).AsClient();

            if (!await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 4040)))
            {
                Console.WriteLine("Failed to connect the target server.");
                return;
            }

            //client.PackageHandler += async (s, p) =>
            //{
            //    Console.WriteLine(p.Text);
            //    await Task.CompletedTask;
            //};
            //client.StartReceive();

            //var hdn = Task.Run(Receive);
            //hdn.Start();



            await client.SendAsync(Encoding.UTF8.GetBytes("Test" + "\r\n"));

            //await client.SendAsync(Encoding.UTF8.GetBytes("Test" + "\r\n"));
            //await Task.Delay(5000);
            //var p = await client.ReceiveAsync();
            //Console.WriteLine(p.Text);
            await Task.Delay(5000);

            while (true)
            {
                var p = await client.ReceiveAsync();

                if (p == null)
                {
                    break;
                }
                Console.WriteLine("接收到的数据:" + p.Text);
            }

            //while (true)
            //{
            //    var p = await client.ReceiveAsync();
            //    Console.WriteLine("接收信息:" + p.Text?.ToString());
            //}
        }
Пример #7
0
        private async Task Send(string message)
        {
            ////await _client.SendAsync(Encoding.UTF8.GetBytes(message + "\r\n"));
            //var data = new TextMessageModel
            //{
            //    LocalName = TbUserName.Text,
            //    TextMessage = message
            //};
            //// 向ChatArea中添加组件
            //WpChatArea.Children.Add(new SendControl(data));
            //CreateUdpClient();

            ////await _client.SendAsync(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data) + "\r\n"));

            var sendPackage = new MessagePackage <TextMessageModel>()
            {
                OpCode      = LbCurrentChat.Content.Equals("All") ? OpCode.All : OpCode.Single,
                MessageType = MessageType.TextMessage,
                Message     = new TextMessageModel()
                {
                    LocalName   = TbUserName.Text,
                    RemoteName  = LbCurrentChat.Content.ToString(),
                    TextMessage = TbSendArea.Text
                }
            };

            WpChatArea.Children.Add(new SendControl(new TextMessageModel()
            {
                LocalName   = TbUserName.Text,
                RemoteName  = LbCurrentChat.Content.ToString(),
                TextMessage = TbSendArea.Text
            }));

            await _client.SendAsync(Encoding.UTF8.GetBytes(sendPackage.ToString()));

            Scr.ScrollToEnd();
        }
Пример #8
0
        private async Task InitTcp()
        {
            var options = new ChannelOptions
            {
                Logger       = NullLogger.Instance,
                ReadAsDemand = true
            };

            _client = new EasyClient <TextPackageInfo>(new LinePipelineFilter(), options).AsClient();

            var connected = await _client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 8888));

            var connectPackage = new MessagePackage <TextMessageModel>()
            {
                OpCode      = OpCode.Connect,
                MessageType = MessageType.TextMessage,
                Message     = new TextMessageModel()
                {
                    LocalName  = TbUserName.Text,
                    RemoteName = "Server"
                }
            };
            await _client.SendAsync(
                new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(connectPackage.ToString())));

            while (true)
            {
                var receivePackage =
                    JsonConvert.DeserializeObject <MessagePackage <TextMessageModel> >((await _client.ReceiveAsync()).Text);

                if (receivePackage.Message == null)
                {
                    continue;
                }
                switch (receivePackage.OpCode)
                {
                case OpCode.DisConnect:
                    MessageBox.Show(receivePackage.Message.TextMessage, receivePackage.Message.LocalName);
                    TbUserName.IsEnabled = true;
                    break;

                case OpCode.Connect:
                    LvOnlineList.Children.Clear();
                    var allItem = new UserItemsControl("All");
                    allItem.setRoteName = SetRoteName;
                    LvOnlineList.Children.Add(allItem);
                    foreach (var userClient in receivePackage.Clients)
                    {
                        var childItem = new UserItemsControl(userClient.Username);
                        childItem.setRoteName = SetRoteName;
                        LvOnlineList.Children.Add(childItem);
                    }

                    TbUserName.IsEnabled = false;
                    break;

                case OpCode.All:
                    this.LbCurrentChat.Content = receivePackage.Message.LocalName;
                    WpChatArea.Children.Add(new MessageControl(new TextMessageModel()
                    {
                        LocalName   = receivePackage.Message.LocalName,
                        TextMessage = receivePackage.Message.TextMessage
                    }));
                    break;

                case OpCode.Single:
                    LbCurrentChat.Content = receivePackage.Message.LocalName;
                    WpChatArea.Children.Add(new MessageControl(new TextMessageModel()
                    {
                        LocalName   = receivePackage.Message.LocalName,
                        TextMessage = receivePackage.Message.TextMessage
                    }));
                    break;
                }
                Scr.ScrollToEnd();

                if (connected)
                {
                    BdConnectState.Background = new SolidColorBrush(Colors.LimeGreen);
                    TbUserName.IsEnabled      = false;
                }
                else
                {
                    BdConnectState.Background = new SolidColorBrush(Colors.OrangeRed);
                    TbUserName.IsEnabled      = true;
                    break;
                }

                await Task.Delay(500);
            }

            //while (true)
            //{
            //    var package = await _client.ReceiveAsync();
            //    //if(package != null) SpChatArea.Text += "Receive:" + package.Text + Environment.NewLine;
            //    var data = JsonConvert.DeserializeObject<TextMessageModel>(package.Text);
            //    if (package != null)
            //    {
            //        WpChatArea.Children.Add(new MessageControl(new TextMessageModel()
            //        {
            //            LocalName = data.LocalName,
            //            TextMessage = data.TextMessage
            //        }));
            //    }
            //    await Task.Delay(500);
            //}
        }
        private async void InitTcpConnectAndReceive()
        {
            var options = new ChannelOptions
            {
                Logger       = NullLogger.Instance,
                ReadAsDemand = true
            };

            _sendTcpClient = new EasyClient <TextPackageInfo>(new LinePipelineFilter(), options).AsClient();

            _connected = await _sendTcpClient.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 8888));

            var connectPackage = new TcpPackage()
            {
                OpCode      = OpCode.Connect,
                LocalName   = TbUserName.Text,
                RemoteName  = "Server",
                MessageType = MessageType.Text
            };

            await _sendTcpClient.SendAsync(
                new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes(connectPackage.ToString())));


            while (true)
            {
                var receivePackage = TcpPackage.JsonToPackage((await _sendTcpClient.ReceiveAsync()).Text);
                if (string.IsNullOrEmpty(receivePackage.Message))
                {
                    continue;
                }

                switch (receivePackage.OpCode)
                {
                case OpCode.Connect:
                    SpOnlineList.Children.Clear();
                    var allItem = new UserItemsControl("All");
                    allItem.setRoteName = SetRoteName;
                    SpOnlineList.Children.Add(allItem);
                    foreach (var onlineClient in receivePackage.Clients)
                    {
                        var childItem = new UserItemsControl(onlineClient.Username);
                        childItem.setRoteName = SetRoteName;
                        SpOnlineList.Children.Add(childItem);
                    }
                    TbUserName.IsEnabled       = false;
                    BtnConnectServer.IsEnabled = false;
                    break;

                case OpCode.DisConnect:
                    MessageBox.Show(receivePackage.Message, receivePackage.LocalName);
                    TbUserName.IsEnabled = true;
                    break;

                case OpCode.All:
                case OpCode.Single:
                    LbChatWith.Content = receivePackage.OpCode == OpCode.All
                            ? receivePackage.RemoteName : receivePackage.LocalName;
                    switch (receivePackage.MessageType)
                    {
                    case MessageType.Text:
                        ChatArea.Children.Add(new ReceiveControl(receivePackage, null));
                        break;

                    case MessageType.Image:
                        // 建立UDP客户端 直接接收消息
                        ReceiveImage(receivePackage: receivePackage);
                        break;

                    case MessageType.File:
                        var res = MessageBox.Show("是否接收文件?", "提示", MessageBoxButton.YesNo,
                                                  MessageBoxImage.Information);
                        if (res == MessageBoxResult.Yes)
                        {
                            // 发送TCP确认连接消息
                            // 创建UDP客户端
                        }
                        break;
                    }
                    break;

                case OpCode.Confirm:
                    switch (receivePackage.MessageType)
                    {
                    case MessageType.Image:
                        var fileName = await SendImage();

                        await Task.Delay(1000);
                        await SendImage(fileName, receivePackage);

                        break;

                    case MessageType.File:
                        break;
                    }
                    break;
                }

                Scr.ScrollToEnd();

                if (_connected)
                {
                    BdConnectState.Background = new SolidColorBrush(Colors.LimeGreen);
                    TbUserName.IsEnabled      = false;
                }
                else
                {
                    BdConnectState.Background = new SolidColorBrush(Colors.OrangeRed);
                    TbUserName.IsEnabled      = true;
                    break;
                }

                //await Task.Delay(1000);
            }
        }
Пример #10
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Background service is started...");

            var address = IPAddress.Parse(_config.ServerIp);

            if (!await _client.ConnectAsync(new IPEndPoint(address, _config.ServerPort), cancellationToken))
            {
                _logger.LogError("Failed to connect to the target server.");
            }

            _client.PackageHandler += async(sender, package) =>
            {
                switch (package.Key)
                {
                case CommandKey.Execute:
                    var command = Command.Parser.ParseFrom(Encoding.UTF8.GetBytes(package.Content));
                    await Execute(command.OperatorId, command.Content);

                    break;

                case CommandKey.Connected:
                    _logger.LogInformation("Connected");
                    break;

                case CommandKey.Pong:
                    var unix = long.Parse(package.Content);
                    _pongTime = DateTimeOffset.FromUnixTimeMilliseconds(unix).UtcDateTime;
                    break;

                default:
                    _logger.LogWarning($"Unknown command:{package.Key}");
                    break;
                }
            };

            _client.StartReceive();

            await _client.SendAsync(Encoding.UTF8.GetBytes($"{CommandKey.Connect} {ClientType.Agent.ToString()}{Package.Terminator}"));

            _pingTimer      = new Timer(SendPing, null, TimeSpan.Zero, TimeSpan.FromSeconds(_pingIntervalSecond));
            _checkPingTimer = new Timer(CheckPong, null, TimeSpan.Zero, TimeSpan.FromSeconds(_checkPingIntervalSecond));

            _client.Closed += async(sender, args) =>
            {
                if (!_shouldReconnect)
                {
                    return;
                }

                _logger.LogError("Connection disconnect.");

                Thread.Sleep(2000);

                if (!await _client.ConnectAsync(new IPEndPoint(address, _config.ServerPort), cancellationToken))
                {
                    _logger.LogError("Failed to reconnect to the target server.");
                }
                else
                {
                    _client.StartReceive();
                    _logger.LogInformation("Connection reconnect.");
                }
            };
        }
Пример #11
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Socket Service is starting.");

            var address = IPAddress.Parse(_serverIp);

            if (!await _client.ConnectAsync(new IPEndPoint(address, _serverPort), cancellationToken))
            {
                _logger.LogError("Failed to connect to the socket server.");
            }

            _client.PackageHandler += async(sender, package) =>
            {
                switch (package.Key)
                {
                case CommandKey.Connected:
                    _logger.LogInformation("Connected");
                    break;

                case CommandKey.Output:
                    var index      = package.Content.IndexOf(' ');
                    var operatorId = package.Content.Substring(0, index);
                    var content    = package.Content.Substring(index + 1, package.Content.Length - index - 1);
                    await _socketHub.Clients.Groups(operatorId).ReceiveMessage(content + Package.Terminator);

                    break;

                case CommandKey.Pong:
                    var unix = long.Parse(package.Content);
                    _pongTime = DateTimeOffset.FromUnixTimeMilliseconds(unix).UtcDateTime;
                    break;

                default:
                    _logger.LogError($"Unknown command:{package.Key}");
                    break;
                }
            };

            _client.StartReceive();

            await _client.SendAsync(Encoding.UTF8.GetBytes($"{CommandKey.Connect} {ClientType.Web.ToString()}{Package.Terminator}"));

            _pingTimer      = new Timer(SendPing, null, TimeSpan.Zero, TimeSpan.FromSeconds(_pingIntervalSecond));
            _checkPingTimer = new Timer(CheckPong, null, TimeSpan.Zero, TimeSpan.FromSeconds(_checkPingIntervalSecond));

            _client.Closed += async(sender, args) =>
            {
                if (!_shouldReconnect)
                {
                    return;
                }

                Thread.Sleep(2000);

                if (!await _client.ConnectAsync(new IPEndPoint(address, _serverPort), cancellationToken))
                {
                    _logger.LogError("Failed to connect to the socket server.");
                }
                else
                {
                    _client.StartReceive();
                }
            };
        }