如何使用windowsphone 8从蓝牙设备连续读取数据
本文关键字:连续 读取 数据 何使用 windowsphone | 更新日期: 2023-09-27 17:59:31
一个小应用程序,我有一个蓝牙设备,它将在我们执行await _socket.OutputStream.WriteAsync(data)
时发送连续数据但我无法通过windows手机连续读取数据。
private async void writeData()
{
string newLabel = "startReading,RFID'n";
var data = GetBufferFromByteArray(Encoding.UTF8.GetBytes(newLabel));
await _socket.OutputStream.WriteAsync(data);
Thread.Sleep(500);
readData();
}
private async void readData()
{
var buffer = new Windows.Storage.Streams.Buffer(2048);
var receivedSize = await _socket.InputStream.ReadAsync(buffer, 2048, InputStreamOptions.ReadAhead);
// string s = Encoding.UTF8.GetString(receivedSize,0,receivedSize.Length);
var dr = DataReader.FromBuffer(buffer);
List<byte> lst = new List<byte>();
byte[] bytes = new byte[] { };
for (int i = 0; i < 2048; i++)
{
//bytes[i]=dr.ReadByte();
lst.Add(dr.ReadByte());
}
byte[] dataAsBytes = lst.ToArray();
// byte[] dataAsBytes = lst.SelectMany(s => System.Text.Encoding.UTF8.GetBytes(s)).ToArray();
string s3 = Convert.ToBase64String(dataAsBytes);
string result = System.Text.Encoding.UTF8.GetString(dataAsBytes, 0, 2048);
Data_txtblcx.Text = result.ToString();
}
让我们试着简化您的代码,看看我们是否不能让它以这种方式工作。以下是我为您准备的几个助手:
public static async Task<byte[]> ReadFromSocket(StreamSocket socket)
{
using (var output = new MemoryStream())
{
var bytesCopied = await RandomAccessStream.CopyAsync(socket.InputStream, output.AsOutputStream());
if (bytesCopied > 0)
return output.ToArray();
}
return new byte[0];
}
public static IAsyncOperationWithProgress<uint,uint> WriteToSocket(StreamSocket socket, byte[] bytes)
{
return socket.OutputStream.WriteAsync(bytes.AsBuffer());
}
要使用它们,您的示例方法看起来更像这样:
private async Task writeData(StreamSocket socket)
{
await WriteToSocket(socket, Encoding.UTF8.GetBytes("startReading,RFID'n"));
await Task.Delay(500);
await readData(socket);
}
private async Task readData(StreamSocket socket)
{
byte[] dataAsBytes = await ReadFromSocket(socket);
Data_txtblcx.Text = Encoding.UTF8.GetString(dataAsBytes, 0, dataAsBytes.Length > 2048 ? 2048 : dataAsBytes.Length);
}
不过,如果您的问题与套接字的处理有关,这对您没有帮助。