title: How to manage XMPP connection
body: <p>I am designing a chat application using ejabberd as XMPP server and Smack 4.1 API. Below is a code snippet for managing connection.</p>
  
  
  
  <pre class="lang-java prettyprint-override"><code>    // Create a connection to the server.com server on 5222 port.
      XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
        .setUsernameAndPassword("user", "password")
        .setServiceName("server.com")
        .setHost("server.com_ip")
        .setPort(5222)
        .setSecurityMode(SecurityMode.disabled)
        .build();
      XMPPTCPConnection conn = new XMPPTCPConnection(config);
      try {
          conn.connect();
          System.out.println("Connection established.");
          conn.login();
          System.out.println("Logged in.");
      } catch (SmackException | IOException | XMPPException e) {
          System.out.println("Connection not established: " + e.getMessage());
      }
  </code></pre>
  
  <p>Some processing for chat and muc.</p>
  
  <pre class="lang-java prettyprint-override"><code>    // Disconnect
      conn.disconnect();
      System.out.println("Connection Closed.");
  </code></pre>
  
  <p><strong>My Requirement:</strong></p>
  
  <ul>
  <li>Once a user logs into the app, they might not log out for months at a time. Exactly the way Whatsapp works.</li>
  </ul>
  
  <p><strong>My question is:</strong></p>
  
  <ul>
  <li>Is it a good idea to keep the connection open as long as user is logged in?</li>
  <li>If not then is it a good idea to open and close the connection for every chat message?</li>
  </ul>
  
  <p><strong>Need Suggestion:</strong></p>
  
  <ul>
  <li>What is the most efficient way to handle a connection with XMPP server?</li>
  </ul>