[英]Starting ServerSocket on Java with User Interface(Swing) Freezes
美好的一天,
我有一个ServerSocket的无限循环,工作正常...问题是当我尝试使用按钮启动ServerSocket时。 我的用户界面“冻结”什么都没有动,但服务器正常运行,这里有一个ScreenShot :
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组件的状态。
查看Swing和Worker线程中的并发性 以及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();
}
举个例子
ServerSocket.accept()
方法是一种阻塞方法。 这意味着Socket s = ss.accept();
停止当前线程,直到打开与服务器套接字的连接。
Swing中的事件调度是单线程的,上面提到的while循环和阻塞操作将使线程保持“繁忙”并阻塞与UI的所有其他交互。
您应该在单独的线程中运行整个while循环。 当您要停止服务器时,还应确保退出while循环,并且线程完成执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.