简体   繁体   English

客户端-服务器-冻结按钮

[英]Client-Server - freezing button

I'm writing a simple client-server appa. 我正在编写一个简单的客户端-服务器应用程序。 It shoud work like that. 它应该像那样工作。 I run the server app than i click button to create server. 我运行服务器应用程序比单击按钮创建服务器。 When server turn on i can the client app and connect to the server. 服务器打开时,我可以使用客户端应用程序并连接到服务器。 Server also have JTextFild tfLog where message log pops out. 服务器还具有JTextFild tfLog,可在其中弹出消息日志。 My problem is that when i click button to create server if freez. 我的问题是,当我单击按钮以创建服务器时,如果是freez。 Image 图片

All looks like this: 一切看起来像这样:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class ServerGui extends JFrame implements ActionListener{

protected JButton bCreateServer;
public static JTextArea taLOg;

public ServerGui(){
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            dispose();
        }
    });
    initLayout();
    setVisible(true);


}

private void initLayout() {
    setSize(600, 400);
    setResizable(false);
    setLayout(null);
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    this.setLocation(dimension.width/2-this.getSize().width/2,
            dimension.height/2 - this.getSize().height/2);

    bCreateServer = new JButton("Utwórz serwer");
    bCreateServer.setBounds(20,20,150,25);
    bCreateServer.addActionListener(this);
    bCreateServer.setActionCommand("Create");
    add(bCreateServer);

    taLOg = new JTextArea();
    taLOg.setEditable(false);
    JScrollPane pane = new JScrollPane(taLOg);
    pane.setBounds(20, 50, 400,300);
    add(pane);
}

public static void main(String args[]){
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new ServerGui();
        }
    });
}

public void insertText(final String line){
    if(SwingUtilities.isEventDispatchThread()){
        taLOg.insert(line, 0);
    }
    else{
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run(){
                taLOg.insert(line, 0);
            }
        });
    }
}

@Override
public void actionPerformed(ActionEvent e) {

    String tmp = e.getActionCommand();
    if(tmp.equals("Create")){

        Server server = new Server(8080);
        if(server.serverCreated){
            insertText("Kliknięto Utwórz serwer\n");
            server.clientsListener();
        }
        else{
            insertText("Nie udało się utworzyć serwera\n");
        }

    }
}
}

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server{
private ServerSocket serverSocket;
private Socket socket;
public Boolean serverCreated = false;
public Server(int port){
    try{
        serverSocket = new ServerSocket(port);
    }
    catch(IOException e){
        System.out.println("Błąd przy tworzeniu gniazda serwerowego.");
        System.exit(-1);
    }
    serverCreated = true;
}
public void clientsListener(){
    try{
        socket = serverSocket.accept();
    }
    catch(IOException e){
        System.out.println(e);
    }

    System.out.println(socket);
    try{
        serverSocket.close();
    }
    catch(IOException e){
        System.out.println("Błąd przy zamykaniu gniazda serwerowego.");
        System.exit(-1);
    }
}
}


import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client{

Socket clientSocket;

public Client(String hostname, int port){
    try{
        clientSocket = new Socket(hostname, port);
    }
    catch(UnknownHostException e){
        System.out.println("Nieznany host.");
    }
    catch(IOException e){
        System.out.println(e);
        System.exit(-1);
    }
    System.out.println(clientSocket);
}

public static void main(String args[]){
    Client client = new Client("localhost", 8080);
}
}

Your actionPerformed handler (which executes on the main UI thread of your application) makes a call to clientsListen() on the server object which then makes a call to .accept(). 您的actionPerformed处理程序(在应用程序的主UI线程上执行)在服务器对象上调用clientListen(),然后在该对象上调用.accept()。 accept() will block until a client connects. accept()将阻塞,直到客户端连接为止。 This is why your GUI is hanging. 这就是GUI挂起的原因。

You need to create a new thread that will execute the code for your server. 您需要创建一个新线程,该线程将为您的服务器执行代码。
Something like this in actionPerformed: 这样的动作在执行

Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
       Server server = new Server(8080);
       if(server.serverCreated){
          server.clientsListener();
       }
    }
});

t.setDaemon(true);
t.start();

Also having the client start the server is a little strange. 也让客户端启动服务器有点奇怪。 As an experiment I can understand it but if you give the client the ability to start the server you should probably give them a way to stop it. 作为一个实验,我可以理解,但是如果您让客户端能够启动服务器,则应该给他们一种停止服务器的方法。 That will involve some sort of IPC between the threads which may be getting away from your concept of simple. 这将在线程之间涉及某种IPC,这可能会偏离您的简单概念。

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

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