用于java服务器的非响应GUI

时间:2014-12-06 07:01:44

标签: java user-interface server

我正在尝试为小项目创建GUI。这个项目是一个java服务器,目前我的代码工作正常,服务器已经连接,除了它之外的一切都没有出现循环,因此创建并显示了GUI的框架,但是你不能在病房之后与它交互。我知道循环在哪里,但我似乎无法找到一种方法让我的服务器监听新客户端,仍然能够与GUI交互。这是我的代码:

public class MainServerFrame {

    private static JFrame frame;
    private static ServerSocket serverSocket = null;
    private static Socket clientSocket = null;
    private static final int maxClientsCount = 999;
    private static final clientThread[] threads = new clientThread[maxClientsCount];
    private static StudentStoring studentDB = new StudentStoring();

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainServer();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static void MainServer() {

        // The default port number.
        int portNumber = 3333;
        try {
            serverSocket = new ServerSocket(portNumber);
        } catch (IOException e) {
            System.out.println(e);
        }
        System.out.println("SERVER ONLINE");
        initialize();
        MainServerFrame window = new MainServerFrame();
        MainServerFrame.getFrame().setVisible(true);
        /*
         * Create a client socket for each connection and pass it to a new client
         * thread.
         */

这里我在哪里创建插座然后进入循环,我可以使用什么样的设计摆脱这个循环?

        while (true) {
            try {
                clientSocket = serverSocket.accept();
                int i = 0;
                for (i = 0; i < maxClientsCount; i++) {
                    if (threads[i] == null) {
                        (threads[i] = new clientThread(clientSocket, threads, studentDB)).start();
                        System.out.println("client " + i + " is connected");
                        break;
                    }
                }
                if (i == maxClientsCount) {
                    PrintStream os = new PrintStream(clientSocket.getOutputStream());
                    os.println("Server too busy. Try later.");
                    os.close();
                    clientSocket.close();
                }
            } catch (IOException e) {
                System.out.println(e);
            }
        }
    }

    /**
     * Initialize the contents of the frame.
     */
    private static void initialize() {
        setFrame(new JFrame());
        getFrame().setBounds(100, 100, 450, 300);
        getFrame().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel lblServer = new JLabel("SERVER:");
        getFrame().getContentPane().add(lblServer, BorderLayout.NORTH);

    }

    public static JFrame getFrame() {
        return frame;
    }

    public static void setFrame(JFrame frame) {
        MainServerFrame.frame = frame;
    }

}

我的客户

import java.awt.Font;

public class MainFrame implements Runnable {
    //declare Jpanel
    private static JFrame frmHome;
    // The client socket
    private static Socket clientSocket = null;
    // The output stream
    static ObjectOutputStream os;
    // The input stream
    static ObjectInputStream is;
    private static BufferedReader inputLine = null;
    private static boolean closed = false;

    public static void main(String[] args) throws IOException{
        // The default port.
        int portNumber = 3333;
        // The default host.
        String host = "localhost";
        /*
         * Open a socket on a given host and port. Open input and output streams.
         */
        try {
          clientSocket = new Socket(host, portNumber);
          is = new ObjectInputStream(clientSocket.getInputStream());
          os = new ObjectOutputStream(clientSocket.getOutputStream());
          os.flush();
          System.out
          .println("CONNECTED TO SERVER\n"
              + "Now using host=" + host + ", portNumber=" + portNumber);
        } catch (UnknownHostException e) {
          System.err.println("Don't know about host " + host);
        } catch (IOException e) {
          System.err.println("Couldn't get I/O for the connection to the host "
              + host);
        }

        /*
         * If everything has been initialized then we want to write some data to the
         * socket we have opened a connection to on the port portNumber.
         */
        if (clientSocket != null && os != null && is != null) {
          /* Create a thread to read from the server. */
          new Thread(new MainFrame()).start();
        }
      }

      public void run() {
        /*
         * Keep on reading from the socket till we receive "Bye" from the
         * server. Once we received that then we want to break.
         */
          MainFrame window = new MainFrame();
          MainFrame.frmHome.setVisible(true);
        String responseLine;
        try {
          while (!closed) {

          }
        } finally{
            try {
                is.close();
                os.close();
                clientSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        }

    public MainFrame() {
        initialize();
    }

    //function to make window visible
    void setVisible() throws IOException {
        main(null);
    }

    private void initialize() {
        //Initialise Main window with 3 options.
        frmHome = new JFrame();
        frmHome.setTitle("Home");
        frmHome.setBounds(100, 100, 300, 372);
        frmHome.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmHome.getContentPane().setLayout(null);
        frmHome.setResizable(false);

        JLabel lblWelcomeToSrs = new JLabel("Welcome to SRS");
        lblWelcomeToSrs.setFont(new Font("Tahoma", Font.PLAIN, 14));
        lblWelcomeToSrs.setBounds(86, 183, 112, 14);
        frmHome.getContentPane().add(lblWelcomeToSrs);

        //initialise all buttons and labels of window.
        JButton btnAdStu = new JButton("Add a student");
        btnAdStu.setBounds(10, 207, 126, 23);
        btnAdStu.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                AddStudentFrame adus;
                try {
                    try {
                        adus = new AddStudentFrame();
                        adus.setVisible();
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    frmHome.setVisible(false);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }
        });
        frmHome.getContentPane().add(btnAdStu);

        JButton btnCheckStud = new JButton("Search / Modify");
        btnCheckStud.setBounds(146, 207, 127, 23);
        btnCheckStud.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                SearchFrame searchFrame;
                searchFrame = new SearchFrame();
                searchFrame.setVisible();
            }
        });
        frmHome.getContentPane().add(btnCheckStud);

        JLabel lblNewLabel = new JLabel("");
        lblNewLabel.setBounds(0, 0, 0, 0);
        frmHome.getContentPane().add(lblNewLabel);

        JLabel lblCreatedByRmi = new JLabel("Created by R\u00E9mi Tuyaerts");
        lblCreatedByRmi.setBounds(147, 318, 184, 14);
        frmHome.getContentPane().add(lblCreatedByRmi);  

        JButton btnNewButton = new JButton("Complete List of Students");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                CompleteListFrame studentList = new CompleteListFrame();
                studentList.setVisible();
            }
        });
        btnNewButton.setBounds(52, 241, 184, 23);
        frmHome.getContentPane().add(btnNewButton);

        // wonderful pictures of his excellence design by Yasser
        JLabel lblNewLabel_1 = new JLabel("");
        Image img = new ImageIcon(frmHome.getClass().getResource("/michaelchung.jpg")).getImage();
        lblNewLabel_1.setIcon(new ImageIcon(img));
        lblNewLabel_1.setBounds(80, 11, 120, 148);
        frmHome.getContentPane().add(lblNewLabel_1);
    }
}

1 个答案:

答案 0 :(得分:1)

我首先要提到的是在方法签名中使用static。他们应该static,并且您 不应该尝试静态访问它们(MainServerFrame.getFrame().setVisible(true);)。取出所有方法签名中的static,添加window.getFrame().setVisible(true);

等方法的访问权限

其次,正在事件调度线程上创建MainServerFrame。 EDT处理所有UI交互。虽然您的代码不完整,但while循环显示在MainServerFrame的构造函数中。这个问题是while循环阻塞事件线程,导致无响应。要修复它,你可以简单地为while循环启动一个新线程。

new Thread(new Runnable(){
    public void run() {
        while (true) {
            ...
        }
    }
}).start();

尝试更新UI的新线程中的任何调用都应该包含在SwingUtilities.invokeLater中。像

这样的东西
new Thread(new Runnable(){
    public void run() {
        while (true) {
            ...
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    label.setText(...);
                }
            });
        }
    }
}).start();

这是一个简单的重构器。我拿出一些代码只是为了让这个例子更简单

public class MainServerFrame {

    private JFrame frame;
    private ServerSocket serverSocket = null;
    private Socket clientSocket = null;
    private int maxClientsCount = 999;
    private JTextArea serverLog = new JTextArea(10, 40);

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainServerFrame app = new MainServerFrame();
                    app.getFrame().setVisible(true);
                    app.startServer();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public MainServerFrame() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(serverLog);
        frame.pack();
        frame.setLocationByPlatform(true);
    }

    public JFrame getFrame() {
        return frame;
    }

    public void startServer() {
         int portNumber = 3333;
        try {
            serverSocket = new ServerSocket(portNumber);
        } catch (IOException e) {
            System.out.println(e);
        }
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        clientSocket = serverSocket.accept();
                        final String data = 
                                (new DataInputStream(clientSocket.getInputStream())).readUTF();
                        SwingUtilities.invokeLater(new Runnable(){
                            public void run() {
                                serverLog.append(data);
                                serverLog.append("\n");
                            }
                        });
                    } catch (IOException e) {
                        System.out.println(e);
                    }
                }
            }
        }).start();
    }
}

更新:简单客户端

import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Cilent {
    public static void main(String[] args) throws Exception {
        Socket socket = new Socket("localhost", 3333);
        Scanner scanner = new Scanner(System.in);
        String data = scanner.nextLine();
        (new DataOutputStream(socket.getOutputStream())).writeUTF(data);
    }
}