1

我首先问了这个问题,我弄清楚了 EDT 是如何工作的,并通过阅读这篇文章开始阅读更多关于 swing 和工作线程的内容。我开始了解它们是如何工作的,并将我的代码固定在它将运行的位置。现在我正在尝试从我的工作线程(服务器)获取信息以更新我的 GUI。尽管我似乎无法解决问题,但我遇到了问题。问题是我需要继续监听新客户端(因为服务器应该处理多个客户端)但是因为那是在一个 while 循环中,我从来没有碰到我的工作线程的返回。我也看不到任何其他设置方式。有人可以看看我的代码并提出一种我可以让它工作的方法吗?

主类

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) {

    }
}
}
4

1 回答 1

2

来自Java 教程

服务器

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 
    }
}
于 2012-05-14T22:22:41.497 回答