简体   繁体   English

在Java GUI中的SwingWorker中运行ServerSocket

[英]Running a ServerSocket in a SwingWorker in Java GUI

I have been trying for a very long time to get the following code to work, with no success. 我已经尝试了很长时间,以使以下代码正常工作,但没有成功。 I would like to open a ServerSocket and have it run in the back ground of my GUI interface. 我想打开一个ServerSocket并使其在我的GUI界面的背景中运行。 I have a start button that is supposed to start the server and a stop button that will stop the server from listening any further for clients that wish to connect. 我有一个应该用于启动服务器的启动按钮和一个停止按钮,该按钮将阻止服务器进一步监听希望连接的客户端。

This is a very basic GUI that has 2 buttons and 2 text fields. 这是一个非常基本的GUI,具有2个按钮和2个文本字段。 The user is required to input a user name and a password that is matched against a database. 要求用户输入与数据库匹配的用户名和密码。 If the details are correct the Server should start. 如果详细信息正确,则服务器应启动。 This however causes the GUI to freeze if the server is not run on a separate Thread. 但是,如果服务器未在单独的线程上运行,这将导致GUI冻结。 I wish to use SwingWorker to do this. 我希望使用SwingWorker来做到这一点。 (Unless there is a better way) (除非有更好的方法)

I however am a little in the deep end of my knowledge concerning this matter. 但是,我对此事的了解还很深。 Any help will be very appreciated. 任何帮助将不胜感激。 Thanks! 谢谢!

public class Server extends JFrame implements ActionListener {

JLabel instructionsLabel;
JLabel passwordLabel;
JPasswordField passwordTF;
JButton shutdownButton;
JButton startupButton;
JLabel usernameLabel;
JTextField usernameTF;

public Server() {
    super("Server");
    initComponents();
}



public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();

    String f = "n";
    ConnectionBean cb = new ConnectionBean();

    char[] a = passwordTF.getPassword();
    String b = new String(a);
    String inputDetails = usernameTF.getText() + b;

    Iterator it = cb.getDetails().iterator();
    while (it.hasNext()) {
        Object next = it.next();
        if (inputDetails.equals(next)) {
            f = "y";
            if (source == startupButton) {
                try {
                    sop.doInBackground();
                } catch (Exception ex) {
                }
                JOptionPane.showMessageDialog(null,
                        "Congratulations! Server started.",
                        "Start-up Message",
                        JOptionPane.INFORMATION_MESSAGE);
            } else if (source == shutdownButton) {
                try {
                    sop.failIfInterrupted();
                } catch (Exception ex) {
                }
                JOptionPane.showMessageDialog(null,
                        "Server shut-down successfully!",
                        "Shut-down Message",
                        JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }
    if (f.equals("n")) {
        JOptionPane.showMessageDialog(null, "Invalid username or password.", "Alert", JOptionPane.WARNING_MESSAGE);
    }
    passwordTF.setText("");
    usernameTF.setText("");
    cb.setCloseConnection(true);
}

// THIS IS WHERE I GET STUCK!

public class ServerOperation extends SwingWorker<Void, Void> {

    ServerSocket ss;
    Socket cs;

    public ServerOperation(ServerSocket ss) {
        this.ss = ss;
    }

    @Override
    protected Void doInBackground() throws Exception {

        return Void;
    }

    public void failIfInterrupted() throws InterruptedException {
        if (Thread.currentThread().isInterrupted()) {
            throw new InterruptedException();
        }
    }
}

The code that I used before, to start the server was this... 我之前用来启动服务器的代码是这样的...

ServerSocket ss;
Socket cs;

public void StartingSer() throws Exception {

    ss = new ServerSocket(7777);

    while (true) {
        cs = ss.accept();
        new ServerTread(cs).start();

    }
}

but this causes the GUI to freeze, because it is not thread safe. 但这会导致GUI冻结,因为它不是线程安全的。

"but this causes the GUI to freeze, because it is not thread safe" “但是这导致GUI冻结,因为它不是线程安全的”

No, this causes the GUI to freeze because this method is executed on the GUI thread. 否,这会导致GUI冻结,因为此方法是在GUI线程上执行的。 You must use a separate thread for it. 您必须为此使用单独的线程。

When the Start button is pressed, create a thread, save the reference to it, and start it. 当按下开始按钮时,创建一个线程,保存对该线程的引用,然后启动它。 When the Stop button is pressed, send interruption signal to that thread. 当按下停止按钮时,向该线程发送中断信号。 That's it. 而已。 No SwingWorker is needed. 不需要SwingWorker。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM