I first asked this question, which I figured out how the EDT works and started reading more on swing and worker threads by reading this. I started to get an understanding of how they work and got my code fixed to where it would run. Now I'm trying to get the information from my worker thread (the server) to update my GUI. I run into a problem though I can't seem to work my way around. The problem is I need to keep listening for new client (As the server is suppose to handle multiple clients) but because that is in a while loop I never hit the return of my worker thread. I can't see any other way to set it up either. Could someone take a look at my code and suggest a way I might be able to get this to work?
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) {
}
}
}