title: Keeping Java Bluetooth connection alive
body: <p>I’m building a simple Java Bluetooth server for my computer using the Bluecove API. I’m building an Android client side app as well but the problem seems to be stemming from the server side app.</p>
  <p>I’m sure someone has posted any answer already somewhere and I’ve tried different solutions rigorously for the past several days and looked at every possible forum but I can’t seem to keep the connection on the socket thread alive.</p>
  <p>I can exchange a message across after a connection is established from android to computer and vice versa from computer to android but immediately after the bytes are exchanged, the Bluecove stack shuts down and closes the socket connection even when I don’t explicitly tell it to connection.close().</p>
  <p>I’ve tried to use a while(some statement is true) loop to keep the connection alive and it no longer shuts down the socket after receiving the first message but it can’t receive any subsequent messages I send from my smartphone to my computer either.  While it is essentially alive, it can’t receive any new messages when I try to send them from the smartphone. Not sure why.</p>
  <p>I'm sorry, this is my first time posting and I'm not sure why the first part of the code does not display properly on the page.</p>
  <p>Code making connection:</p>
  <pre class="lang-java prettyprint-override"><code>public BluetoothServer() {
      try {
          service = (StreamConnectionNotifier) 
              Connector.open(&quot;btspp://localhost:&quot; + new UUID(0x1101).toString() + 
                                  &quot;;name=SampleServer&quot;);
          
          System.out.println(&quot;open connection&quot;);
  
          while (runState == true) {
          
              connection = (StreamConnection) service.acceptAndOpen();
                  
              //send a greeting across to android
              outputStream = connection.openOutputStream();
              String greeting = &quot;JSR-82 RFCOMM server says hello&quot;;
              outputStream.write(greeting.getBytes());
              
              //run thread that listens for incoming bytes through socket connection
              Thread t = new Thread(new ConnectedThread(connection));
              t.start();                
          }
              
      } catch(IOException e) {}
  }
  </code></pre>
  <p>THREAD CODE FOR LISTENING TO INCOMING DATA</p>
  <pre class="lang-java prettyprint-override"><code>public void run() {
      try {    
          //open input stream to listen to data
          inputStream = connection.openInputStream();              
                                        
          byte buffer[] = new byte[1024];
          int bytes_read = inputStream.read(buffer);
  
          String received = new String(buffer, 0, bytes_read);
          System.out.println(&quot;received: &quot; + received);
              
      } catch(IOException e) {}
  }
  </code></pre>