我无法使用 PrintWriter 或任何其他输出流在服务器和客户端程序之间发送消息。如果我使用 println("abc") 通信它可以正常工作,但如果我使用 print("abc\r\n")、print("abc\n") 或 print("abc\r" 则它不起作用)。我所说的“它不起作用”的意思是 readLine() 不会结束,因为它似乎看不到“换行符”字符并且它仍在等待“\r”或“\n”
为了更清楚,我将简单地在下面放一些代码: 客户端:
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(); // read the text from client
System.out.println(textFromClient);
String textToClient = "Recieved";
out.print(textToClient + "\r\n"); // send the response to client
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
服务器:
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" ); // send to server
System.out.println(in.readLine()); // read from server
out.close();
in.close();
read.close();
socket.close();
}
}
我想使用 print() + "\r\n" 而不是 println() 因为我正在编写的服务器程序要求从服务器发送到客户端的消息需要在末尾包含 "\r\n",例如。“这是从服务器到客户端的消息\r\n”。我认为 println() 和 print("\r\n") 是一样的,所以我认为我不应该使用 println() + "\r\n",否则会有 2 个换行符。(虽然我不知道客户端如何从服务器读取,因为我被要求只编写服务器程序。他们将编写客户端来测试我的服务器程序。)但是,我应该发送包含“\ r\n" 最后但 readLine() 似乎无法识别它。那么我能用它做什么呢?
如果你不明白我的问题,你可以试试上面的代码,你就会明白我的意思。