美好的一天,
我的 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 Swing和 Worker 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/