[英]Send String through Bluetooth From Java Server to Android Client
使用藍牙將數據從服務器發送到客戶端時,我遇到了問題。
我想每5秒從PC服務器向Android客戶端發送360字符串。 但是我只能發送一個字符串,尤其是在'\\ n'之后,然后服務器關閉。 有人可以幫助我理解此代碼嗎? 實際上,我只是從這里獲取此代碼。
這是我的服務器代碼。
public class SimpleSPPServer {
//start server
private void startServer() throws IOException{
//Create a UUID for SPP
UUID uuid = new UUID("1101", true);
//Create the servicve url
String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: "+dev.getBluetoothAddress());
System.out.println("Remote device name: "+dev.getFriendlyName(true));
/*
//read string from spp client
InputStream inStream=connection.openInputStream();
BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
String lineRead=bReader.readLine();
System.out.println(lineRead);
*/
//send response to spp client
**String message = "-0.145 \n";
byte[] msgBuffer = message.getBytes();
OutputStream outStream=connection.openOutputStream();
outStream.write(msgBuffer);**
//PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
//pWriter.write("Response String from SPP Server\r\n");
//pWriter.flush();
//pWriter.close();
streamConnNotifier.close();
}
基本上,我想將粗體部分修改為這一部分:
Byte [] msgBuffer;
OutputStream outStream;
for(int i=0;i<5;i++)
{
String message = "-0.145" + i;
msgBuffer = message.getBytes();
outStream=connection.openOutputStream();
outStream.write(msgBuffer);
}
但是它不能接受多個數據。 這是我的客戶端:
try {
inStream = btSocket.getInputStream();
//outStream = btSocket.getOutputStream();
BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
String lineRead = bReader.readLine();
newNumber = Double.valueOf(lineRead);
numbertime = (double) 0;
DataPoint v = new DataPoint(numbertime,newNumber);
mlii.appendData(v, true, 1);
System.out.println("data"+v);
//System.out.println("I got the text from server = "+lineRead);
//out.append("I got the text from server = "+lineRead);
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
這個庫對藍牙非常https://github.com/palaima/AndroidSmoothBluetooth
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.