我试图通过蓝牙传输长字符串(2286字节)。关于通过蓝牙接收长json字符串,我有点问题。好吧,不是问题,因为它正在接收它,但是它接收它的方式。我想知道是否可以在一次转移中接收更多字节,或者它是否只是一个限制。
好的,所以在c#方面......这是服务器循环..
_screenWriterCallBT("Bluetooth Server started, waiting for clients..");
BluetoothListener blueListener = new BluetoothListener(mUUID);
blueListener.Start();
BluetoothClient conn = blueListener.AcceptBluetoothClient();
_screenWriterCallBT("Bluetooth Client has connected");
Stream mStream = conn.GetStream();
while (true)
{
try
{
byte[] recieved = new byte[1024];
mStream.Read(recieved, 0, recieved.Length);
string content = Encoding.ASCII.GetString(recieved);
_screenWriterCallBT("Recieved: " + content + "via bluetooth");
ParseJson parseJson = new ParseJson();
JsonReturn = parseJson.InitialParsing(content); //parse message
byte[] sent = Encoding.ASCII.GetBytes(JsonReturn);
mStream.Write(sent, 0, sent.Length);
_screenWriterCallBT("Test" + sent.Length);
string messageSent = Encoding.ASCII.GetString(sent);
_screenWriterCallBT("sent via Bluetooth: " + messageSent);
}
catch (IOException exception)
{
_screenWriterCallBT("Bluetooth Client has disconnected. Exception:" + exception + "\n");
}
}
似乎有效。
_screenWriterCallBT("Test" + sent.Length); // says 2286 bytes on the long string i'm trying to send.
在Android方面,我有一个服务器监听和发送:
public void run() {
byte[] buffer;
int bytes;
while (true) {
try {
buffer = new byte[1024];
// Read from the InputStream
bytes = mmInStream.read(buffer);
System.out.println(bytes);
if(bytes != 0)
listener.messageReceivedFromServer(MESSAGE_READ, bytes, -1, buffer);
} catch (IOException e) {
break;
}
}
}
它工作,并接收字节,但它以奇怪的方式接收它们。
System.out.println(bytes); prints 1010, 1010, 266
所以,基本上我每次都会得到一个截断的json字符串,而我无法将其转换为JSON对象。我知道收到消息的时间,它将它写入临时字符串,并测试它是否是一个有效的json对象然后继续有效。无论如何,我想我会来检查一下,如果我做错了什么或者能改变某些东西,任何Stack溢出大师是否可以发光?
干杯 本
答案 0 :(得分:1)
您需要阅读直到收到所有数据,您只需从流中读取一次,从而最终得到部分数据。您已在while(true)
循环中部分执行此操作,但您不知道何时完成数据传输,例如您已发现。
从c#侧可以看到所需内容:
var sb = new StringBuilder();
while(mStream.DataAvailable())
{
byte[] received = new byte[1024];
mStream.Read(received, 0, received.Length);
sb.Append(Encoding.ASCII.GetString(received));
}
var receivedString = sb.ToString();
_screenWriterCallBT("Received: " + receivedString + "via bluetooth");
ParseJson parseJson = new ParseJson();
JsonReturn = parseJson.InitialParsing(receivedString); //parse message
在android方面做同样的事情。