I have a problem using PrintWriter or any other output stream to send a message between the server and the client program. It works correctly if I use println ("abc") for communication, but it does not work if I use print ("abc \ r \ n"), print ("abc \ n") or print ("abc \ r ")). What I mean by “doesn't work” is that readLine () will not end because it seems like it is not seeing the “new line” character and it is still waiting for “\ r” or “\ n”
To make this clearer, I will simply put some codes in the following: Client:
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(1234);
} catch (IOException e) {
System.err.println("Could not listen on port: 1234.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
}
System.out.println("Connected");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String textFromClient;
textFromClient = in.readLine();
System.out.println(textFromClient);
String textToClient = "Recieved";
out.print(textToClient + "\r\n");
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
Server:
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
try {
socket = new Socket("localhost", 1234);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection");
}
System.out.println("Connected");
String textToServer;
textToServer=read.readLine();
out.print(textToServer + "\r\n" );
System.out.println(in.readLine());
out.close();
in.close();
read.close();
socket.close();
}
}
print() + "\ r\n" println(), , , , , , "\ r\n" , . msgstr " \r\n". , println() print ( "\ r\n" ), , println() + "\ r\n", . ( , , . .) , "\ r\n" , readLine(), , . , ?
, , , .