title: Java how to always listen for responses from async server socket
body: <p>Im tryng to build an async java client socket, which is always listening for responses from a server. 
   My java program has a GUI so I understand I can not simply put the read method in a thread or runnable because it will block my gui from showing, etc.. I've tried using a swingworker and also an executorservice but it has not worked.
   Any help would be greatly appreciated, here's some code!</p>
  
  <pre><code>public class ClientWindow {
  
  //Variable declarations
  public Selector selector;
  public SocketChannel channel;
  
  //Connects when program starts up..
      btnConnectActionPerformed (ActionEvent evt){
          selector = Selector.open();
          channel = SocketChannel.open();
          channel.configureBlocking(false);
          channel.register(selector, SelectionKey.OP_CONNECT);
          channel.connect(new InetSocketAddress(getProperties.server, port));
  
          connect(channel);
          //..stuff to make gui let me know it connected
        }
  
  //connect method
   private void connect(SocketChannel channel) throws IOException {
      if (channel.isConnectionPending()) {
          channel.finishConnect();
      }
      channel.configureBlocking(false);
      channel.register(selector, SelectionKey.OP_WRITE);
   }
  
  //read method
   private void read(SocketChannel channel) throws IOException 
   {
  
      ByteBuffer readBuffer = ByteBuffer.allocate(1000);
      readBuffer.clear();
      int length;
  
      try {
          length = channel.read(readBuffer);
      } catch (IOException e) {
          JOptionPane.showMessageDialog(null, "Trouble reading from server\nClosing connection", "Reading Problem", JOptionPane.ERROR_MESSAGE);
          channel.close();
          btnDiscon.doClick();
          return;
      }
      if (length == -1) { //If -1 is returned, the end-of-stream is reached (the connection is closed).
          JOptionPane.showMessageDialog(null, "Nothing was read from server\nClosing connection", "Closing Connection", JOptionPane.ERROR_MESSAGE);
          channel.close();
          btnDiscon.doClick();
          return;
      }
  
      readBuffer.flip();
      byte[] buff = new byte[1024];
      readBuffer.get(buff, 0, length);
  
      String buffRead = new String(buff);
      System.out.println("Received: " + buffRead);
   }
  
  }
  </code></pre>