0

Am I doing this right? When I try to run this on my computers loopback address I'm getting a "connection reset" error.

public class DateTimeClient {
public static void main(String[] args) throws IOException {
    int port = Integer.parseInt(args[0]);
    String host = args[1];
    try {
        System.out.println("Connecting....\n");
        Socket socket = new Socket(host, port);
        PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
        System.out.println("Date: " + reader.read());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}


public class DateTimeServer {
public static void main(String[] args) {
    int portNum = Integer.parseInt(args[0]);
    try {
        ServerSocket socket = new ServerSocket(portNum);
        Socket client = socket.accept();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                client.getInputStream()));
        PrintWriter writer = new PrintWriter(client.getOutputStream());
        Date date = new Date();
        writer.print(date.toString());
    } catch(Exception e) {
        e.printStackTrace();
    }
}
}

I grab the port to run the server on, the port to connect to and the host as arguments in the main method, create sockets and use BufferedReader and PrintWriter. I followed Oracle's tutorial on this pretty closely so I'm not sure where I coulda made a mistake.

1
  • Why is your PrintWriter writer initialized using different constructor in server than one used in client? Commented Nov 7, 2015 at 2:48

2 Answers 2

3

@EJP is correct, but I think that the actual problem is that the server side is neither closing or flushing writer. When the server exits, the TCP/IP connection gets closed (by the server-side OS) without any data having been written to the socket. The client side JVM sees a reset connection and throws an exception.

Solution: Close your streams properly on the server side and the client side should see the data. (Flushing would work too ... but if you neglect to close the streams in all cases, you risk problems with server-side file descriptor leaks. Hence, closing is the best solution.)

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

1 Comment

The client side JVM doesn't see a closed socket. It sees a reset connection and throws an exception. The reset could be due to the peer not closing the socket and Windows kindly resetting it instead, or three or four other things.
2

You're only reading one character, not a date. Try sending and receiving a line.

Comments

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.