Java如何始终侦听来自异步服务器套接字的响应

时间:2015-01-16 23:19:02

标签: java sockets asynchronous client

我尝试构建一个异步java客户端套接字,它始终监听来自服务器的响应。  我的java程序有一个GUI,所以我理解我不能简单地将read方法放在一个线程或runnable中,因为它会阻止我的gui显示等等。我已经尝试过使用swingworker和executorservice但它有没工作。  任何帮助将不胜感激,这里有一些代码!

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

}

1 个答案:

答案 0 :(得分: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();

            }
        }
    }

}
相关问题