0

So the the server program consists of the following code:

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

public class TimeServer {

    public static void main(String[] args) {

        try {

            //Create sockets
            ServerSocket ss = new ServerSocket(60000);
            Socket rs = ss.accept();
            //create streams
            BufferedInputStream bs = new BufferedInputStream(rs.getInputStream());
            InputStreamReader isr = new InputStreamReader(bs);
            BufferedOutputStream bos = new BufferedOutputStream(rs.getOutputStream());
            PrintWriter pw = new PrintWriter(bos);
            //set timeout
            rs.setSoTimeout(20000);
            int c = 0;
            StringBuilder sb = new StringBuilder();
            //while loop reads in a character until a period (includes period)  
            while (((char) c != '.')) {
                c = isr.read();
                //append each char to a string builder
                sb.append((char) c);
            }
            //convert stringbuilder to string
            String str = sb.substring(0);
            //If string equals "time." returns time else error message
            if (str.compareTo("time.") == 0) {
                Date now = new Date();
                pw.print("time is: " + now.toString());
                pw.flush();
            }
            else {
                pw.print("Invalid syntax: connection closed");
                pw.flush();
            }
            //close socket
            rs.close();
            //close serversocket
            ss.close();
        } catch(IOException i) {
            System.out.println(i.getMessage());
        }
    }
}

The code for the client is:

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

public class TimeClient {

    public static void main(String[] args) {

        try {
            //create socket
            Socket sock = new Socket("localhost", 60000);
            //create streams
            BufferedInputStream bis = new BufferedInputStream(sock.getInputStream());
            InputStreamReader isr = new InputStreamReader(bis);
            BufferedOutputStream bos = new BufferedOutputStream(sock.getOutputStream());
            PrintWriter pw = new PrintWriter(bos);
            //set timeout
            sock.setSoTimeout(20000);
            //write argument to stream, argument should be "time." to recieve time
            pw.write(args[0]);
            pw.flush();
            int c = 0;
            StringBuilder sb = new StringBuilder();
            //while loop reads each character into stringbuilder
            while ((c != -1)) {
                c = isr.read();
                sb.append((char) c);
            }
            //stringbuilder converted to string and printed
            String str = sb.substring(0);
            System.out.println(str);
            //socket closed
            sock.close();
        } catch(IOException i) {
            System.out.println(i.getMessage());
        }
    }
}

The problem is that if I run each program in a separate cmd.exe, they do not communicate despite using localhost as the IP address. I can't seem to find the logical error in the code which causes this and wondered if anyone could help?

9
  • 1
    You need to close pw so it gets flushed, not the socket. Don't ignore exceptions. Commented Jul 10, 2019 at 12:05
  • No exceptions were thrown, the code compiled fine. The problem is that both programs don't communicate. Commented Jul 10, 2019 at 12:07
  • 1
    The code compiling fine has nothing to do wth no exceptions being thrown, and with those catch clauses you have no idea whether one was thrown or not. Commented Jul 10, 2019 at 12:08
  • 1
    Of course, or print the stack trace. Anything rather than just ignoring it. Commented Jul 10, 2019 at 12:10
  • 1
    So you still haven't fixed the issue mentioned in my first comment. Commented Jul 10, 2019 at 12:13

1 Answer 1

1

The problem is that you are using a BufferedOutputStream and you close the socket immediately after writing on the PrintWriter. What you have written remains in the buffer and the socket is closed before anything has been sent to the client.

You need to flush before closing in order to force the content of the buffer to be sent:

...
//close socket
pw.flush();
rs.close();
...

TimeClient contains a minor error: you loop receiving until you get a -1 which is correct, but you append that -1 to the StringBuilder which is wrong. It should be:

//while loop reads each character into stringbuilder
while(true){
c = isr.read();
if (c == -1) { break; }
sb.append((char) c);
}

But this should never prevent the text to be displayed...

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

2 Comments

I flushed after all write methods in my code however I am faced with a blank screen
@ABC123 I can no longer reproduce. I have taken your code for both client and server. I ensured that both jars had been generated started in one cmd window java -jar timeserver.jar, in a second one java -jar timeclient.jar time. and got in that latter: time is: Wed Jul 10 15:08:48 CEST 2019?. The last ? is the representation for '\uffff'. I am preparing an edit about that.

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.