2015-01-16 52 views
0

Im试着构建一个异步java客户端套接字,该套接字始终侦听来自服务器的响应。 我的Java程序有一个图形用户界面,所以我明白我不能简单地把读取方法放在一个线程或runnable,因为它会阻止我的GUI显示,等等。我试过使用一个摆动工具,也是一个executorservice,但它没有工作。 任何帮助将不胜感激,这里有一些代码!Java如何总是侦听来自异步服务器套接字的响应

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); 
} 

} 

回答

0

所以我设法让它工作,可能是缺少一两行或某物。不知道,因为它基本上是我以前尝试做的。

//* Nested class to constantly listen to server *// 
public class ReaderWorker extends SwingWorker<Void, Void> { 

    private SocketChannel channel; 

    public ReaderWorker(SocketChannel channel) { 
     this.channel = channel; 
    } 

    @Override 
    protected Void doInBackground() throws Exception { 
     while (true) { 
      java.awt.EventQueue.invokeLater(new Runnable() { 
       public void run() { 
        System.out.println("Executed"); 
        try { 
         read(channel); 
        } catch (IOException ex) { 
         Logger.getLogger(ClientWindow.class.getName()).log(Level.SEVERE, null, ex); 
        } 
       } 
      }); 
      try { 
       Thread.sleep(2000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 

      } 
     } 
    } 

} 
相关问题