JavaFx 和套接字监听器

标签 java multithreading sockets user-interface javafx

我们正在开发一个客户端-服务器应用程序,它必须同时使用 GUI 和 CLI。 我们对 CLI 没有任何问题,但我们在使用 JavaFX 实现它时遇到了困难:

我们的服务器向客户端发送一些对象(通过套接字),这些对象必须被处理。

这是我们的 SocketServerListener(和编写器):

public class SockeServerListener extends Thread implements ServerListener{
    private CliController controller;
    private ObjectInputStream in;
    private ObjectOutputStream out;

    public SocketServerListener(Socket server, CliController controller) throws UnknownHostException, IOException {
        this.controller = controller;
        this.out = new ObjectOutputStream(server.getOutputStream());
        this.in = new ObjectInputStream(server.getInputStream());
    }

    public void publishMessage(String message) throws IOException, RemoteException {
        out.writeObject(message);
        out.flush();
    }

    public void run() {
        try {
            while (true) {
                Dialogue dialogue = (Dialogue) in.readObject();
                controller.parseDialogue(dialogue);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


}

SocketServerListener 由 Controller 实例化,该 Controller 执行“执行”接收到的对象,更新界面(Cli/GUI)

public void parseDialogue(Dialogue dialog) {
        dialog.execute(view); //view is an interface extended by both the Cli and GUI
        this.canWrite = true;
    }

正如我所说,这在 CLI 中运行得很好,但在 JavaFX 中会抛出异常

Exception in thread "Thread-7" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-7

我们尝试使用用于生成所有 GUI 的类作为 Controller ,但没有任何(积极的)结果。 我们如何实例化一个线程,以便它可以与 JavaFX 一起工作并调用显示我们需要的屏幕的方法?

谢谢

最佳答案

Not on FX application thread

为您提供问题的原因。

根据 Node 的 Javadoc类:

Node objects may be constructed and modified on any thread as long they are not yet attached to a Scene in a Window that is showing. An application must attach nodes to such a Scene or modify them on the JavaFX Application Thread.

使用Platform.runLater在 FX 应用程序线程上执行代码并查看 javafx.concurrent进一步实用程序类的包。

关于JavaFx 和套接字监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37764061/

相关文章:

java - Android 客户端/Java 服务器套接字; android发送但不接收?

java - 使用cql java驱动程序在cassandra中插入数据而不用单引号引起来

java - 删除 Jframe 面板

java - JList/ListModel getElements 不起作用

java - 如何通过 Activity 的上下文获取类中的 TextView

python - 在类中实例化线程

java - 如何在 android 流式套接字连接上获得超时异常?

c - recv 停止或不返回所有数据(C 代码)

java - 如何使用多线程将List中的数据插入到DB表中以提高性能?

c - 使用用户输入在 C 中跨线程同步数据