0
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();
    }
}

I tried making a server which either takes Strings from a Scanner or sends the last String with a Printer to the specific client. The method accept() is called at the beginning and the server is working. But when the timer stops, the client should get closed but the server hangs and stops working. These are the client methods:

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();
            }
    }
}

Can anyone tell why it stops working and how to fix it. I'm new to this server topic.

EisiGames
  • 1
  • 4

0 Answers0