我正在关注有关StreamSockets的Windows通用示例。它告诉我如何连接到服务器并作为客户端写入服务器,但它没有告诉我如何从服务器读取响应。示例是https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/StreamSocket
在控制台应用程序中,我可以使用StreamReader和StreamWriter来读取和写入套接字流。看起来Universal App中的可比数据是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 ...这是唯一的选择吗?
答案 0 :(得分:0)
250是任意的,但读卡器上有一个设置,它会在收到一个或多个字节后停止。
reader.InputStreamOptions = InputStreamOptions.Partial;
await reader.LoadAsync(250);
Response.Text = "\"" + reader.ReadString(reader.UnconsumedBufferLength) + "\" read successfully.";