使用用户界面(Swing)在Java上启动ServerSocket冻结 [英] Starting ServerSocket on Java with User Interface(Swing) Freezes
问题描述
美好的一天,
我有一个无限循环的ServerSocket,工作正常...问题是当我尝试使用按钮启动ServerSocket时.我的用户界面冻结"什么都没有动,但服务器正常运行,这里有一个 ScreenShot :
I have an infinite loop for a ServerSocket, working fine... The problem is when I try to start the ServerSocket with a button. My user interface "Freeze" don't move, anything, but the server is up and fine, here I have a ScreenShot:
http://i.gyazo.com/15d331166dd3f651fc7bda4e3670be4d.png
当我按下按钮"Iniciar"时,意味着启动服务器,用户界面冻结(ServerSocket无限循环). 我无法更改我的代码,因为它可以正常工作.
When I press the button "Iniciar" means Start server, the User Interface Freezes (ServerSocket infinite loop). I can't change my code because its working fine.
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冻结而无法正常工作.
appendString(); Is for add some text to the JTextPane, but doesnot work because the UI freezes.
有什么方法可以做一个不会因无限循环而冻结的用户界面?
Is there any way to do an user interface that don't freeze by the infinite loop?
谢谢!
推荐答案
Swing是一个单线程框架,这意味着在事件调度线程的上下文中执行的任何阻塞或长时间运行的操作都将阻止它处理事件队列,从而您的应用程序挂起.
Swing is a single threaded framework, meaning any blocking or long running operation executed within the context of the Event Dispatching Thread will prevent it from processing the Event Queue, making your application hang.
它也不是线程安全的,因此您永远不要尝试从EDT外部修改任何UI组件的状态.
It's also not thread safe, so you should never try and modify the state of any UI component from out side of the EDT.
看看 Swing中的并发和
要启动它,可以使用类似... To start it, you could use something like... 例如 这篇关于使用用户界面(Swing)在Java上启动ServerSocket冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!public void iniciarServer() {
ServerSocketWorker worker = new ServerSocketWorker(textAreaToAppendTo);
worker.execute();
}