2016-11-19 70 views
2

我正在構建與android設備(作爲客戶端)通信的簡單java服務器。目前,我可以通過藍牙將來自手機(客戶端)的信息發送至我的電腦(服務器)。問題是我無法將來自服務器的消息發送回客戶端。我正在使用bluecave庫。這裏是我的代碼java藍牙服務器發回消息給客戶端

public class MainTest { 
    UUID uuid = new UUID("8848",true); 
    public static void main(String[] args) { 
     LocalDevice local = null; 
     try { 
      local = LocalDevice.getLocalDevice(); 
     } catch (BluetoothStateException e) { 
      e.printStackTrace(); 
     } 
     System.out.println("Serverted:\n" +local.getBluetoothAddress() +"\n"+local.getFriendlyName()); 
     MainTest ff = new MainTest(); 
     while (true) { 
      ff.startserver(); 
     } 
    } 

    public void startserver() { 
     try { 
      String url = "btspp://localhost:" + uuid + ";name=File Server"; 
      StreamConnectionNotifier service = (StreamConnectionNotifier) Connector.open(url); 

      StreamConnection con = service.acceptAndOpen(); 
      OutputStream dos = con.openOutputStream(); 
      InputStream dis = con.openInputStream(); 

      while (true) { 
       byte buffer[] = new byte[1024]; 
       int bytes_read = dis.read(buffer); 
       String received = new String(buffer, 0, bytes_read); 
       System.out.println("Message:"+ received); 

       if("a".equals(received)) { 
        dos.write("sdfsd".getBytes()); 
        dos.flush(); 
       } 
      } 
      // con.close(); 
     } catch (IOException e) { 
      System.err.print(e.toString()); 
     } 
    } 

我還試圖用PrintWriter更新的代碼,但還是沒有反應......

public static void startserver() { 
     try { 
      String url = "btspp://localhost:" + uuid + ";name=TTT"; 
      StreamConnectionNotifier service = (StreamConnectionNotifier) Connector.open(url); 

      StreamConnection con = service.acceptAndOpen(); 
      DataOutputStream dos = con.openDataOutputStream(); 
      InputStream dis = con.openInputStream(); 
      PrintWriter pWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(dos)), true); 
      while (true) { 
       byte buffer[] = new byte[10]; 
       int bytes_read = dis.read(buffer); 
       String received = new String(buffer, 0, bytes_read); 
       System.out.println("Message:"+ received); 

       pWriter.write("testString"); 
       pWriter.flush(); 

      } 
      // pWriter.close(); 
      // con.close(); 


      // con.close(); 
     } catch (IOException e) { 
      System.out.println(e.getMessage()); 
     } 
    } 
+0

[通過藍牙從Java服務器發送文本到Android客戶端]可能的重複(http://stackoverflow.com/questions/10929767/send-text-through-bluetooth-from-java-server-to-android-client ) –

回答

相關問題