2

When a user connects to my server, I'm accepting the connection, storing the connected clients details in an arraylist then im trying to send that list to the client to create an asynchronous list. However, when I try to send the list it breaks the connection and causes the error;

java.net.SocketException: Socket is closed

My server class;

        while (true) {                           
            Socket clientSocket = serverSocket.accept();
            ServerClientComs clientThread = new ServerClientComs(clientSocket);
            getUsername(clientSocket, clientThread);
            updateList();                
            try {
                clientThread.sendList(connections);                
                clientThread.initialiseCommunication();                     
                clientThread.start();                                 
            } 
            catch (IOException error) {
                System.out.println("Server: Unable to initialise client thread! - " + error);

            }
        }

ServerClientComs Class;

public ServerClientComs(Socket clientSocket) {
    super();
    this.client = client;
    this.clientSocket = clientSocket;
}

public void initialiseCommunication() throws IOException {
    output = new PrintWriter(this.clientSocket.getOutputStream(), true);
    input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}

public void sendList(ArrayList connections) throws IOException
{
    oos = new ObjectOutputStream(this.clientSocket.getOutputStream());
    oos.writeObject(connections);   
    oos.close();
}

Been playing about with this for a good hour, getting annoying now. any help is greatly appreciated!

1 Answer 1

3

A 'Socket closed' exception means that the application that caught the exception closed the socket and then kept trying to use it. Please note that closing the input or output stream of a socket closes the other stream and the socket as well. According to your statements seems you close the stream before using the socket to send data.

Sign up to request clarification or add additional context in comments.

4 Comments

in my getusername function, i close the BufferedReader input, so im therefore closing the socket?
I think due to it's prevalence that's the problem, to get more insight please take a look at this.
@horHAY> I'm glad you did it and hope my answer has been useful.
'Due to its prevalence'?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.