Java服务器在断开连接时挂起

时间:2017-03-01 15:07:07

标签: java sockets serversocket

public class Server {

static Socket client;
static ServerSocket server;
static boolean running = false;
static boolean connected = false;
static String direction;
static Timer timer;
static String temp;
static Scanner in;
static PrintWriter out;

public void game() throws IOException{
    in = new Scanner(client.getInputStream());
    out = new PrintWriter(client.getOutputStream(), true);
    timer = new Timer(20, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(running){
                if(in.hasNextLine()){
                    temp=in.nextLine();
                    if(temp.equalsIgnoreCase("finished")) running = false;
                    if(temp.equalsIgnoreCase("set")){
                        if(in.hasNextLine()) direction=in.nextLine();
                    }
                    if(temp.equalsIgnoreCase("get")){
                        out.println(direction);
                    }
                    temp="null";
                }
            } else {
                try {
                    client.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                connected = false;
                timer.stop();
            }
        }

    });
}

public void connect(){
    try {
        server = new ServerSocket(1337);
        connected = true;
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void accept(){
    if(!connected) connect();
    try{
        if(client==null){
            client = server.accept();
        }
        game();
        running = true;
        timer.start();
    } catch ( IOException e ) {
        e.printStackTrace();
    }
}

我尝试制作一台服务器,它可以从扫描仪中获取字符串,也可以将带有打印机的最后一个字符串发送到特定的客户端。方法accept()在开始时调用,服务器正在工作。但是当计时器停止时,客户端应该关闭,但服务器挂起并停止工作。 这些是客户端方法:

public void connect(){
    if(!connected){
        try{
            server = new Socket("localhost", 1337);
            connected = true;
            out = new PrintWriter (server.getOutputStream(), true);
            in = new Scanner(server.getInputStream());
        } catch (IOException e){
            System.err.println("||Client>> No server found");
        }
    }
}

public void disconnect(){
            if(connected){
            try {
                server.close();
                out.println("finished");
                connected=false;
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

任何人都可以告诉它为什么停止工作以及如何解决它。我是这个服务器主题的新手。

0 个答案:

没有答案