title: RFCOMM | How to get notification when Client gets disconnected and write data to client?
body: <p>I am using RFCOMM Server application on linux side so any mobile application can get connect with it and does the communication.
  I have used rfcomm-server.c example to test and have modified it little</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;bluetooth/bluetooth.h&gt;
  #include &lt;bluetooth/rfcomm.h&gt;
  
  struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
  char buf[1024] = { 0 };
  int s, client, bytes_read, status;
  socklen_t opt = sizeof(rem_addr);
  
  void vCreateConnection()
  {
      // allocate socket
      s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
  
      // bind socket to port 1 of the first available 
      // local bluetooth adapter
      loc_addr.rc_family = AF_BLUETOOTH;
      loc_addr.rc_bdaddr = *BDADDR_ANY;
      loc_addr.rc_channel = (uint8_t) 1;
      bind(s, (struct sockaddr *)&amp;loc_addr, sizeof(loc_addr));
  
      // put socket into listening mode
      listen(s, 1);
  
      // accept one connection
      client = accept(s, (struct sockaddr *)&amp;rem_addr, &amp;opt);
      ba2str( &amp;rem_addr.rc_bdaddr, buf );
      fprintf(stderr, "accepted connection from %s\n", buf);
  
  }
  
  void vCloseConnection()
  {
      close(client);
      close(s);
  }
  
  int main(int argc, char **argv)
  {
  
      vCreateConnection();
      while(1)
      {
          printf("\r\nClear buffer");
          memset(buf, 0, sizeof(buf));
  
          // read data from the client
          bytes_read = read(client, buf, sizeof(buf));
          if( bytes_read &gt; 0 ) {
              printf("received [%s]\n", buf);
              //if(status == 0)
              {
                  printf("send [%s]\n", buf);
                  status = write(s, &amp;buf, 1);
                  //status is not making any difference.
                  //if(status &lt; 0)
                      //break;
              }
          }
          if(buf[0] == 'q')
          {
              vCloseConnection();
              vCreateConnection();
          }
          else if(buf[0] == 'x')
              break;
      }
      // close connection
      close(client);
      close(s);
      return 0;
  }
  </code></pre>
  
  <ol>
  <li>Here I am able to connect fine and sending data from BlueTerm Android App. But when I disconnect from device from android then I am not sure if my linux application can detect that client is disconnected so I can put it back into accepting new connection mode by closing current active session?</li>
  <li>I am also not sure which is correct way to response back client is this function to write back client?</li>
  </ol>
  
  <p><pre><code>status = write(s, &amp;buf, 1);</pre></code></p>