Home > front end >  Java - Getting error "Socket is closed" when my Client class connects on my Server class
Java - Getting error "Socket is closed" when my Client class connects on my Server class

Time:02-04

I made two classes in Java named Server.java and Client.java. The Server is listening to a port and is waiting for a Client to connect (using sockets). When the client connects he can type a pair of numbers separated by "space" and if that pair exists in my edge_list.txt file the Server returns "1" to the client, if not it returns "0". After I completed my initial project I wanted to also use Threads so that it can handle multiple users at once, but when the Client connects I get -> java.net.SocketException: Socket is closed.

I reviewed my code and try using flush() instead of close(). Also, I thought I was closing the socket before the user can read the file, but it didn't seem that was the case. Below I will have the Server.java code block and not the Client.java, cause it doesn't seem to be the problem.

Server.java

import java.io.*;
import java.net.*;
import java.util.*;

public class Server {
    private static final int PORT = 9999;

    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("Server is listening on port "   PORT);

            while (true) {
                try (Socket socket = serverSocket.accept()) {
                    System.out.println("Client connected: "   socket);
                    new ClientHandler(socket).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class ClientHandler extends Thread {
        private Socket socket;
        ClientHandler(Socket socket){
            this.socket = socket;
        }
        @Override
        public void run() {
            try {
                //Creating Sockets and Streams
                InputStream input = socket.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                OutputStream output = socket.getOutputStream();
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(output));

                while (socket.isConnected() && !socket.isClosed()) {
                    //Reading what the Client types
                    String request = reader.readLine();
                    //Split the values with "space" and store them in an array,
                    //then parse those values to two integers
                    String[] values = request.split(" ");
                    int A = Integer.parseInt(values[0]);
                    int B = Integer.parseInt(values[1]);
                    //Check if the pair in the file exists using checkPairInFile() method
                    boolean exists = checkPairInFile(A, B);
                    //if it does print 1 else 0
                    writer.println(exists ? "1" : "0");
                    //Flush the output to send the response back to the client
                    writer.flush();
                }

                //Print the disconnected user
                System.out.println("Client disconnected: "   socket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    private static boolean checkPairInFile(int A, int B) {
        try (Scanner scanner = new Scanner(new File("edge_list.txt"))) {
            //Scanning the file lines
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                //Split the values with "space"
                String[] values = line.split(" ");
                //Parse the values from String -> Int
                int a = Integer.parseInt(values[0]);
                int b = Integer.parseInt(values[1]);
                //if both exist return true
                if (A == a && B == b) {
                    return true;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }
}

P.S. Thanks in advance for your help, in case this is problem with my Client.java file I will update the post.

CodePudding user response:

This part:

try (Socket socket = serverSocket.accept()) {
    System.out.println("Client connected: "   socket);
    new ClientHandler(socket).start();
}

accepts a socket, then prints a message, then starts a new thread, then closes the socket. At some point later the new thread finishes starting up and tries to use the socket and realizes it was already closed.

try (...) {...} (officially called try-with-resources) always closes the things when it gets to the }. That's the point of it. If you don't want to close the socket at the } then you shouldn't use this type of statement.

  • Related