簡體   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