创建一个等待任务以发送消息

时间:2018-07-17 10:42:51

标签: c# uwp stream async-await task

我做了一个客户端服务器asynchro。连接已打开,客户端向服务器发送字符串。但是现在我想在用户单击buttonOK时向他发回一些东西

我尝试执行一个等待任务,以将邮件从服务器发送给客户端,如下所示:

private async void buttonOk_ClickAsync(object sender, RoutedEventArgs e)
    {
    // Get all strokes on the InkCanvas.
    IReadOnlyList<InkStroke> currentStrokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();
    Boolean flag = false;


    if (currentStrokes.Count > 0)
    {
        Windows.Storage.StorageFolder picturesLibrary = KnownFolders.PicturesLibrary;
        StorageFolder savedPicturesFolder = await picturesLibrary.CreateFolderAsync("New Pictures", CreationCollisionOption.OpenIfExists);
        StorageFile imageFile = await savedPicturesFolder.CreateFileAsync("NewImage.jpg", CreationCollisionOption.ReplaceExisting);

        CanvasDevice device = CanvasDevice.GetSharedDevice();
        CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)inkCanvas.ActualWidth, (int)inkCanvas.ActualHeight, 96);

        using (var ds = renderTarget.CreateDrawingSession())
        {
            ds.Clear(Colors.White);
            ds.DrawInk(inkCanvas.InkPresenter.StrokeContainer.GetStrokes());
        }

        using (var fileStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite))
        {
            await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Jpeg, 1f);
        }

        flag = true;
    }

    if (flag)
    {
        var res = await senddata();
        flag = false;
    }

    inkCanvas.InkPresenter.StrokeContainer.Clear();
    GrdLogo.Visibility = Visibility.Visible;
    GrdApp.Visibility = Visibility.Collapsed;

}

private async Task<string> senddata()
  {
  Stream streamOut = socket.OutputStream.AsStreamForWrite();
  StreamWriter writer = new StreamWriter(streamOut);
  string request = "Hello client";
  await writer.WriteLineAsync(request);
  await writer.FlushAsync();
  return null;
  }

但是我的服务器没有发送并挂起。有人可以解释一下为什么吗? 谢谢您的帮助

2 个答案:

答案 0 :(得分:0)

@Xavier Xie:这是我的服务器端代码

string response;
using(Stream inputStream = streamSocket.InputStream.AsStreamForRead())    
{
   using(StreamReader streamReader = new StreamReader(inputStream))
   {
      response = await streamReader.ReadLineAsync();
   }
}
this.txtBlk_Events.Text += response;

然后我收到以下消息:“远程主机必须关闭现有连接”

答案 1 :(得分:0)

好的,我找到了解决方案。我犯的错误,我忘记让客户端处于监听模式。 之后,我的服务器也可以向我的客户端发送消息。 这篇文章对我有帮助:Network connection with UWP Apps