【发布时间】:2015-10-30 19:10:36
【问题描述】:
我正在关注有关 StreamSockets 的 Windows 通用示例。它告诉我如何连接到服务器并作为客户端写入服务器,但它没有告诉我如何读取服务器的响应。例子是https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/StreamSocket
在控制台应用程序中,我可以使用 StreamReader 和 StreamWriter 来读取和写入套接字流。看起来通用应用程序中的可比性是 DataReader/DataWriter。但是我的 DataReader 缓冲区中没有显示任何数据。特别是 reader.UnconsumedBufferLength 返回 0。我的代码的另一个问题是我正在单击一个按钮来打印响应缓冲区。我希望我的程序在接收数据时自动打印响应缓冲区。我假设我需要创建一个事件侦听器,但这也不在示例中。这是我连接后调用的打印缓冲区方法(当我使用连接方法连接到远程 FTP 服务器时,我没有遇到任何异常。我假设它也已连接,因为 Socket 不为空)。:
private async void PrintBuffer_Click(object sender, RoutedEventArgs e)
{
StreamSocket socket;
object outValue;
//If we havent initialized socket, dont use the socket
if (!CoreApplication.Properties.TryGetValue("clientSocket", out outValue))
{
Response.Text = "Please connect before sending.";
return;
}
socket = (StreamSocket)outValue;
// Create a DataReader if we did not create one yet. Otherwise use one that is already cached.
DataReader reader;
if (!CoreApplication.Properties.TryGetValue("clientDataReader", out outValue))
{
reader = new DataReader(socket.InputStream);
CoreApplication.Properties.Add("clientDataReader", reader);
}
else
{
reader= (DataReader)outValue;
}
// Read the locally buffered data to the network.
try
{
uint unread = reader.UnconsumedBufferLength;
await reader.LoadAsync(unread);
Response.Text = "\"" + reader.ReadString(unread) + "\" read successfully.";
}
catch (Exception exception)
{
// If this is an unknown status it means that the error if fatal and retry will likely fail.
if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
{
throw;
}
Response.Text = "Send failed with error: " + exception.Message;
}
}
更新:我在这里找到了另一个示例:https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/SocketActivityStreamSocket/cs/SocketActivityStreamSocket/Scenario1_Connect.xaml.cs 和 Microsoft 在其 LoadAsync 函数中随机尝试 250...这是唯一的选择吗?
【问题讨论】:
标签: c# sockets stream client win-universal-app