0

I am attempting a client/server type chat box (using GUI's). I won't get into details of the multi-threading I used in the program since I believe it is not part of the problem (I hope not) and it will be good amount of code to post. Anyways, for both my client and my server I create a socket, and some other stream classes within a try block, and some reason the sockets close after the catch blocks. PS I do NOT call socket.close() method anywhere that could end if early

Server, this is ran into a constructor of one of my class. It breaks down into, my main has the actually server stuff on a different thread, (like my previous post) it is a fix so that the gui can load and run the server stuff without one waiting on the other. Anyways, without all that detail, here is my code

    public ChatAppProtocol(Socket sock) 
    {
        super("ChatAppServer");
        // this also has a clas var of Socket
        this.sock = sock;

        try (
            PrintWriter output = new PrintWriter(this.sock.getOutputStream(), true);
            BufferedReader input = new BufferedReader(new InputStreamReader(this.sock.getInputStream())) ;
        ) 
        {
           // first stream of a string is the username loging in from client 
           String name = input.readLine();
           // this returns false, so its not closed
           System.out.println("closed?: " + this.sock.isClosed());

        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        // PROBLEM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        // closed after the catch blocks  before methods even ends
        // p.s. i also plan on using the socket in another method but can't since it closes
        System.out.println("closed?: " +this.sock.isClosed());

    }

now my client

@FXML
private void login() 
{
        this.name = this.username.getText().trim();
        this.portnum = Integer.parseInt(this.port.getText());
        this.name = this.username.getText().trim();
        this.ipaddr = this.ip.getText().trim();

        try (t
            Socket socket = new Socket(this.ipaddr, this.portnum);
            PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
        ) 
        {
            this.sock = socket;
            output.println(this.name);
            // this returns false, not closed
            System.out.println("closed?: " +this.sock.isClosed());
        } 
        catch (UnknownHostException e) 
        {
            System.err.println("Problem at ip: " + this.ipaddr);
            System.exit(1);
        } 
         // PROBLEM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        // returns true here, closes before methods end and i cant reuse it
        System.out.println("IS IT CLOSED!!!!!! " + this.sock.isClosed());
    }
}

so, any reason why both this different class, different files, different project sockets close after try-catch blocks? Can't find answer online, and been on it for a while and I am stuck. I found out about this problem after seeing this on the server side console

  java.net.SocketException: Socket is closed
at java.net.Socket.getOutputStream(Socket.java:943)
at chatappserver.ChatAppProtocol.run(ChatAppProtocol.java:62)
7

2 Answers 2

4

Because you're creating socket with the brackets of the try block, it is automatically closed upon exiting the block. Instead, try creating it inside the block itself and it shouldn't be closed:

try {
    this.sock = new Socket(this.ipaddr, this.portnum);
    PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
    output.println(this.name);
} catch (UnknownHostException e) {
    System.err.println("Problem at ip: " + this.ipaddr);
    System.exit(1);
}
// this.sock should still be open at this point.

Have a read of the Java tutorial on try-with-resources for more information on why you're getting your current behaviour.

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

11 Comments

This why wont work for me. The try block wont let me do the this.sock = new blank blank. I get IDE errors, it seems like it only allows me to create a variable then allocate it vs doing it this, :( sucks I know hats why I did it the way I did or else this would be best!
I get: "illegal start of type = expected ----
illegal start of type = expected on my netbeans 8 IDE
And you're sure you're using the same syntax as in my answer? Could you upload a screenshot of the error?
here is ss, sorry I don't know any other way to give it to you, also ignore all my weird extra code lol drive.google.com/file/d/0B2TiGzeynAl2QVF4Qk9FZWNuRzQ/… @DanielGibbs
|
0

You are using try-with-resources, which is roughly an equivalent of:

    try
    {
        this.sock = new Socket(this.ipaddr, this.portnum));
        output.println(this.name);
        // this returns false, not closed
        System.out.println("closed?: " +this.sock.isClosed());
    } 
    catch (UnknownHostException e) 
    {
        System.err.println("Problem at ip: " + this.ipaddr);
        System.exit(1);
    } finally {
        if (this.sock != null)
          this.sock.close();
    }

Just initialize the socket outside the resources clause of try (...) and it won't get closed

1 Comment

@Dariuzs getting rid of the braces fixes it :)

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.