繁体   English   中英

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

[英]Java how to always listen for responses from async server socket

我正在尝试构建一个异步Java客户端套接字,该套接字始终在侦听服务器的响应。 我的Java程序具有GUI,所以我了解我不能简单地将read方法放在线程或可运行程序中,因为它会阻止我的gui显示,等等。 。 任何帮助将不胜感激,这是一些代码!

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

}

因此,我设法使其正常运行,可能丢失了一两行或几行。 不确定,因为这基本上是我以前尝试过的方式。

   //* 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();

            }
        }
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM