[英]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.