1

I am trying to write a simple client server which will echo back the users request with the string “Response : ” appended to it.

Their are similar questions up that i have looked at but i am having trouble understanding what is going on. I am trying to write this but cant get it to work. Mainly because I am very confused about what is happening.

I Have commented my code as best i could to try explain what i think is happening. I am not sure what the problem is when i run this and enter a message i do not get a response

Client

public class Client {

public void go() {

    try {
        //Create a Socket with ip and port number
        Socket s = new Socket("127.0.0.1", 4242);

        //Get input from user
        Scanner in = new Scanner(System.in);
        System.out.println("Please enter a message");
        String clientMessage = in.nextLine();

        //Make a printwriter and write the message to the socket
        PrintWriter writer = new PrintWriter(s.getOutputStream());
        writer.write(clientMessage);
        writer.close();

        //StreamReader to read the response from the server
        InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
        BufferedReader reader = new BufferedReader(streamReader);

        //Get the response message and print it to console
        String responseMessage = reader.readLine();
        System.out.println(responseMessage);
        reader.close();

    } catch (IOException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }

}

public static void main(String[] args) {
    Client c = new Client();
    c.go();
}

}

Server

public class Server {

public void go() {
    try {
        //Make a ServerSocket to listen for message
        ServerSocket ss = new ServerSocket(4242);

        while (true == true) 
        {
            //Accept input from socket
            Socket s = ss.accept();

            //Read input from socket
            InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
            BufferedReader reader = new BufferedReader(streamReader);                
            String message = reader.readLine();

            //get the message and write it to the socket as response
            PrintWriter writer = new PrintWriter(s.getOutputStream());
            String response = "Response : " + message;
            writer.println(response);
            writer.close();

        }
    } catch (IOException ex) {
        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public static void main(String[] args) {
    Server server = new Server();
    server.go();
}

}
4
  • 1
    It's a bit difficult when you've got a client acting as both a client & a server but to start with, your client and server in you Client code is using the same port number. Big Problem. Commented May 3, 2017 at 19:35
  • You told us what you are trying to do, and you showed us code, but you did not tell us what is going wrong. There is no question. "I am having trouble understanding what is going on" is not a question. Commented May 3, 2017 at 19:57
  • @ Mike Nakis the problem is nothing happens when I try to get a response Commented May 3, 2017 at 20:00
  • 2
    first off, what does while (true == true) mean? Also change writer.write(clientMessage); to writer.println(clientMessage); write doesn't append \n to the end of it. When you call readLine() it keeps reading up until the line terminator. If it never receives it, then it will sit there doing nothing. Commented May 3, 2017 at 23:02

1 Answer 1

3

Remove sock and serverSock from your client code and use s.getInputStream.

Socket is bi-directional on both sides, so just as you do not need a new one on the server when sending back the message, you do not need a new one for receiving it on the client either.

EDIT

Also, "Closing the returned OutputStream will close the associated socket." (docs for getOutputSteam), so do not close the writer, just flush it.

Server can work in its current form, and Client starts working with the minor changes (println and flush):

//Create a Socket with ip and port number
Socket s = new Socket("127.0.0.1", 4242);

//Get input from user
Scanner in = new Scanner(System.in);
System.out.println("Please enter a message");
String clientMessage = in.nextLine();

//Make a printwriter and write the message to the socket
PrintWriter writer = new PrintWriter(s.getOutputStream());
writer.println(clientMessage); // <- println
writer.flush();                // <- flush

//StreamReader to read the response from the server
InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);

//Get the response message and print it to console
String responseMessage = reader.readLine();
System.out.println(responseMessage);
reader.close();
writer.close();                // <- new location for close (*)

(*) Using close inside the main try block is not considered safe, as whenever there is an exception, these lines just will not run (also, if you use any kind of smart IDE, it probably points out that the Socket object itself, and the Scanner are not closed at all). Further reading: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

So at the end the Client could rather look like this, following a more "contemporary" approach:

try (
    Socket s = new Socket("127.0.0.1", 4242);
    Scanner in = new Scanner(System.in);
    PrintWriter writer = new PrintWriter(s.getOutputStream());
    InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
    BufferedReader reader = new BufferedReader(streamReader);
) {
    //Create a Socket with ip and port number

    //Get input from user
    System.out.println("Please enter a message");
    String clientMessage = in.nextLine();

    //Make a printWriter and write the message to the socket
    writer.println(clientMessage);
    writer.flush();

    //StreamReader to read the response from the server

    //Get the response message and print it to console
    String responseMessage = reader.readLine();
    System.out.println(responseMessage);
} catch (IOException ex) {
    ex.printStackTrace(); // (**)
}

(**) I am absolutely sure that you have not checked the log, otherwise you would have known about closing the Socket prematurely. When experimenting with small pieces of code, I would not suggest hiding the exceptions in obscure logs. In fact I usually just write "throws Exception" everywhere (including main, that is possible too) and let JRE dump everything into my face.

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

3 Comments

I have removed this but now nothing hapens
@MichaelGrinnell yes, you will need the println too, as suggested by WalterM
Thank you so much, you have cleared allot up for me and I will throw exceptions clear across the room in future :)

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.