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();
}
}
while (true == true)mean? Also changewriter.write(clientMessage);towriter.println(clientMessage);write doesn't append\nto the end of it. When you callreadLine()it keeps reading up until the line terminator. If it never receives it, then it will sit there doing nothing.