gpt4 book ai didi

java - 在 Java 上启动 ServerSocket 并使用用户界面 (Swing) 卡住

转载 作者:行者123 更新时间:2023-12-01 11:36:27 25 4
gpt4 key购买 nike

美好的一天,

我的 ServerSocket 有一个无限循环,工作正常...问题是当我尝试使用按钮启动 ServerSocket 时。我的用户界面“卡住”什么都没有动,但服务器正常运行,这里我有一个屏幕截图:

http://i.gyazo.com/15d331166dd3f651fc7bda4e3670be4d.png

当我按下“Iniciar”按钮意味着启动服务器时,用户界面卡住(ServerSocket 无限循环)。 我无法更改我的代码,因为它工作正常。

    public static void iniciarServer() {

try {
appendString("\nServidor iniciado.");
System.out.println("asdasd");
} catch (BadLocationException e1) {
e1.printStackTrace();
}

try {
ss = new ServerSocket(1234, 3);
while (true) {
System.out.println("Esperando conexiones...");
appendString("\nEsperando conexiones...");
Socket s = ss.accept();
System.out.println("Conexión entrante: " + s.getRemoteSocketAddress());
appendString("\nConexión entrante: " + s.getRemoteSocketAddress());

conexiones++;
//System.out.println("Debug: conexiones SERVER: " + conexiones);
MultiThread mt = new MultiThread(s, conexiones);
mt.start();
///////////////////////////////////////////////////////////////
}
} catch (IOException e) {
System.out.println("Error Server: " + e.getMessage());
} catch (BadLocationException e) {
e.printStackTrace();
}
stopServer();
}

appendString();用于向 JTextPane 添加一些文本,但由于 UI 卡住而不起作用。

有没有办法让用户界面不会因无限循环而卡住?

谢谢!

最佳答案

Swing 是一个单线程框架,这意味着在事件调度线程上下文中执行的任何阻塞或长时间运行的操作都将阻止它处理事件队列,从而使您的应用程序挂起。

它也不是线程安全的,因此您永远不应该尝试从 EDT 外部修改任何 UI 组件的状态。

看看Concurrency in SwingWorker Threads and SwingWorker了解更多详情

public class ServerSocketWorker extends SwingWorker<Void, String> {

private JTextArea ta;

public ServerSocketWorker(JTextArea ta) {
this.ta = ta;
}

@Override
protected void process(List<String> chunks) {
for (String text : chunks) {
ta.append(text);
}
}

@Override
protected Void doInBackground() throws Exception {
ss = new ServerSocket(1234, 3);
while (true) {
publish("\nEsperando conexiones...");
Socket s = ss.accept();
publish("\nConexión entrante: " + s.getRemoteSocketAddress());

conexiones++;
//System.out.println("Debug: conexiones SERVER: " + conexiones);
MultiThread mt = new MultiThread(s, conexiones);
mt.start();
///////////////////////////////////////////////////////////////
}
}

@Override
protected void done() {
stopServer(); //??
}
}

要启动它,您可以使用类似...

public void iniciarServer() {
ServerSocketWorker worker = new ServerSocketWorker(textAreaToAppendTo);
worker.execute();
}

举个例子

关于java - 在 Java 上启动 ServerSocket 并使用用户界面 (Swing) 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29935628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com