我首先问this问题,我弄清楚了 EDT 是如何工作的,并开始通过阅读 this 来阅读有关 swing 和工作线程的更多信息。 。我开始了解它们的工作原理,并将我的代码固定到它将运行的位置。现在我正在尝试从我的工作线程(服务器)获取信息来更新我的 GUI。我遇到了问题,尽管我似乎无法解决。问题是我需要继续监听新客户端(因为服务器应该处理多个客户端),但因为这是在 while 循环中,所以我从未返回工作线程。我也看不到任何其他方法来设置它。有人可以看一下我的代码并建议我可以让它工作的方法吗?
Main.class
package com.sever.core;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class Main {
private SocketManager network;
private Window window;
public static void main(String[] args){
Main main = new Main();
main.runGUI();
main.runServer();
}
private void runGUI(){
//Runs the swing components in the EDT.
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
window = new Window();
window.setVisible(true);
}
});
}
private void runServer(){
//Runs the Server process on a worker thread.
SwingWorker<String, String> server = new SwingWorker(){
@Override
protected Object doInBackground() throws Exception {
network = new SocketManager(25595);
/*
* Here is the problem. I need to keep running this code so,
* that I can let multiple clients connect. However,
* it then never reaches the return.
*/
while(true){
try {
network.setSocket(network.getServerSocket().accept());
addUser(network.getSocket());
} catch (Exception e) {
System.out.println("Failed to connect.");
}
}
return network.getMessage();
}
@Override
protected void done(){
try {
window.updateChat(get().toString());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
server.run();
}
private void addUser(Socket s){
try {
Scanner input = new Scanner(s.getInputStream());
network.addUser(input.nextLine());
} catch (Exception e) {
}
}
}
最佳答案
服务器
public class Server {
public static void main(String[] args) {
ServerSocket server = new ServerSocket(4444);
while(true) {
new ServerThread(server.accept()).start();
}
}
}
服务器线程
public class ServerThread implements Runnable {
private InputStream in;
private OutputStream out;
public ServerThread(Socket client) {
in = client.getInputStream();
out = client.getOutputStream();
}
public void run() {
// do your socket things
}
}
关于Java 线程 - 获取 ServerSocket 输入来更新 Swing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10590379/