我正在做一个Xamarin Android应用,我的目标是在两个设备之间发送数据。我的代码基于官方蓝牙聊天
https://developer.xamarin.com/samples/monodroid/BluetoothChat/
现在我想发送文件,所以我修改了Run()
类的ConnectedThread
方法以接收大量字节,以模拟文件。
以下是代码:
const string TAG = "ConnectedThread";
private BluetoothSocket _socket;
Stream inStream;
Stream outStream;
private BluetoothTransactionService _service;
public override void Run()
{
Log.Info(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[10240];
int bytes;
// Keep listening to the InputStream while connected
while (_service.GetState() == BluetoothTransactionService.STATE_CONNECTED)
{
try
{
// Read from the InputStream
MemoryStream memoryStream = new MemoryStream(2048);
// Here is the bug.
while((bytes = inStream.Read(buffer,0, buffer.Length) ) > 0)
{
memoryStream.Write(buffer, 0, bytes);
}
buffer = memoryStream.ToArray();
// Send the obtained bytes to the UI Activity
_service._handler
.ObtainMessage(BluetoothConstants.MESSAGE_READ, buffer.Length, -1, buffer)
.SendToTarget();
}
catch (Java.IO.IOException e)
{
Log.Error(TAG, "disconnected", e);
_service.ConnectionLost();
break;
}
}
}
输入流的inStream.Read
方法正在等待数据,而while循环永远不会被破坏,我不明白为什么。对我来说,while循环将会中断,因为没有更多的数据可供阅读。
感谢您的帮助。