简体   繁体   English

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

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

Im tryng to build an async java client socket, which is always listening for responses from a server. 我正在尝试构建一个异步Java客户端套接字,该套接字始终在侦听服务器的响应。 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. 我的Java程序具有GUI,所以我了解我不能简单地将read方法放在线程或可运行程序中,因为它会阻止我的gui显示,等等。 。 Any help would be greatly appreciated, here's some 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);
 }

}

So I managed to get it working, probably was missing a line or two or something. 因此,我设法使其正常运行,可能丢失了一两行或几行。 Not sure since it's basically how i was tryng to do it before. 不确定,因为这基本上是我以前尝试过的方式。

   //* 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.

相关问题 如何用Java创建一个不断从服务器监听的套接字? - How to create a socket that constantly listen from the Server in Java? 如何在套接字编程中从Server(server.java)socket连续侦听PHP(client.php)套接字 - how to continuously listen PHP(client.php) socket from Server(server.java)socket in socket programming 如何收听异步服务器端Java Controller? - How to listen to async server side Java Controller? 如何使用服务器套接字在Java中一次监听一个客户端? - how to listen to one client at a time in java using server socket? Java服务器在需要时侦听套接字 - Java server listen to socket when needed Java TCP客户端-服务器连接:始终打开以侦听服务器 - Java TCP Client-Server Connection: always open to listen from server 如何使用Java Socket监听80端口 - How to listen to port 80 by using Java Socket 服务器如何知道客户端的端口号,它将使用它使用 Java 编程套接字将响应发送到客户端? - How the server knows the port number of the client in which it will use it to send the responses to the client using java programming socket? Java HttpURLConnection如何从服务器接收多个响应 - Java HttpURLConnection how to receive multiple responses from server java 7 socket listen异常 - java 7 socket listen exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM