通过蓝牙从Java Server发送字符串到Android客户端

时间:2015-09-08 05:34:09

标签: java android bluetooth server client

我遇到了一个问题,即使用蓝牙从服务器发送数据到客户端。

我想每隔5秒从PC服务器向Android客户端发送360字符串。但我只能在' \ n'之后发送一个字符串,然后关闭服务器。 谁能帮助我理解这段代码?实际上我只是从here获得此代码。

这是我的服务器代码。

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() + ".");
}

1 个答案:

答案 0 :(得分:0)

此库适用于蓝牙https://github.com/palaima/AndroidSmoothBluetooth