Joe*_*oey 5 java sockets client-server readline printwriter
我无法使用PrintWriter或任何其他输出流在服务器和客户端程序之间发送消息.如果我使用println("abc")进行通信,它可以正常工作,但如果我使用print("abc\r \n"),print("abc \n")或print("abc\r \n")它就无法正常工作).我的意思是"它不起作用"是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();
}
}
Run Code Online (Sandbox Code Playgroud)
服务器:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我想使用print()+"\ r \n"而不是println(),因为我写的服务器程序要求从服务器发送到客户端的消息最后需要包含"\ r \n",例如."这是从服务器到客户端的消息\ r \n".我认为println()与print("\ r \n")相同,所以我不认为我应该使用println()+"\ r \n",否则它将有2个换行符.(虽然我不知道客户端如何从服务器读取,因为我只被要求只编写服务器程序.他们会编写客户端来测试我的服务器程序.)但是,我应该发送包含"\"的消息r \n"最后但readLine()似乎无法识别它.那我该怎么办呢?
如果你不理解我的问题,你可以尝试上面的代码,你会知道我的意思.
Vis*_*ire 12
从客户端写入服务器后刷新():
out.print(textToServer + "\r\n" ); // send to server
out.flush(); // here, it should get you going.
Run Code Online (Sandbox Code Playgroud)
有效.