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)); } } }
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()); //} }
private async void DoReceive() { while (!_cts.IsCancellationRequested && IsConnected) { var package = await _client.ReceiveAsync(); if (package == null) { break; } if (package.IsOutputStream) { if (!_hasWriteFile) { _fileStream = new FileStream(package.OutputFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); _hasWriteFile = true; } //写入文件 await _fileStream.WriteAsync(package.Body, 0, package.Body.Length); //刷新到磁盘 if (!package.IsComplete) { continue; } await _fileStream.FlushAsync(); } //返回为Strem,需要逐步进行解析 _resp.Header = new FastDFSHeader(package.Length, package.Command, package.Status); if (!_context.IsOutputStream) { _resp.LoadContent(Configuration, package.Body); } Reset(); _tcs.SetResult(_resp); } }
private void DoReceive() { Task.Run(async() => { while (!_cancellationTokenSource.IsCancellationRequested && IsRunning) { var package = await _client.ReceiveAsync(); if (package.IsOutputStream) { if (!_hasWriteFile) { _fileStream = new FileStream(package.OutputFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); _hasWriteFile = true; } //写入文件 _fileStream.Write(package.Body, 0, package.Body.Length); //刷新到磁盘 if (package.IsComplete) { _fileStream.Flush(); } else { continue; } } //返回为Strem,需要逐步进行解析 var response = _context.Response; response.Header = new FastDFSHeader(package.Length, package.Command, package.Status); if (!_context.IsOutputStream) { response.LoadContent(Option, package.Body); } Reset(); _taskCompletionSource.SetResult(response); } }, _cancellationTokenSource.Token); }
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); } }