Home > Software design >  Java sockets - Output stream from server to client via method call
Java sockets - Output stream from server to client via method call

Time:06-10

I have this code that keeps the server running in a thread. The purpose of leaving the server open is that I want to send something to the client through this server via a static method.

Here's the thread:

public class SampleThread extends Thread {

    static PrintWriter out;
 
    public void run() {
        while(true) {
            try(
                ServerSocket server = new ServerSocket(SAMPLE_PORT);
                Socket socket = server.accept();
            ){
                out = new PrintWriter(socket.getOutputStream());
                while(true) {
                    //nothing, just keeps the server running (is this working?)
                }
            }catch (IOException e){
                    //JDialog message that says retrying to connect
            }
        }
    }
}

Here's the static method that's that uses the server to send something the client:

static void sendToClient(String s1, String s2){
    out.write(s1   "\n");
    out.write(s2   "\n");
    out.flush();
}

When it comes to the purpose of sending something to the client from the server via a method call, it works. However, if I close the connection on the client's side, the program above can't throw the IOException. the out.write() method is not even throwing any error at all, it just accepts whatever I pass to it.

What can I do to make it so that the catch (IOException e) will still be triggered once the client closes the connection?

CodePudding user response:

Nevermind. Adding a socket input read in the empty while(true){} block did the trick.

Here's what I added on it:

socket.getInputStream().read();

Then on the catch block I added an out = null:

catch (IOException e){
    //JDialog message that says retrying to connect
    out = null;
}

After that I just need to check if out != null before executing what's in the static method:

static void sendToClient(String s1, String s2){
    if(out != null) {
        out.write(s1   "\n");
        out.write(s2   "\n");
        out.flush();
    }
}
  • Related