我写了一个简单的套接字教程,关于在客户端和服务器之间发送/接收消息。我使用DataOutputStream在流中写入字符串,但是如果我使用 BufferedReader ,则服务器无法读取它
如果我使用PrintWriter进行写(客户端),则它可以工作。
怎么了非常感谢。
1.客户:
client = new Socket("localhost", 1982);
DataOutputStream opStr = new DataOutputStream(client.getOutputStream());
//pw = new PrintWriter(client.getOutputStream(), true);
//pw.println("Hello, is there anybody out there?");// Can be read by BufferedReader
opStr.writeUTF("Hello, anyone there?");
opStr.flush();// BufferedReader can't read it
2.服务器:
openServer();// port 1982
while(true) {
Socket clientSocket = null;
// listen to connection.
clientSocket = echoServer.accept();
DataInputStream inStr = new DataInputStream(
clientSocket.getInputStream());
//System.out.println("M1: Got msg " + inStr.readUTF());// It showed the content
BufferedReader bfReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("got Messages: ");
String strLine = "";
// Don't show anything
while ((strLine = bfReader.readLine()) != null) {
System.out.println(strLine);
}
}
最佳答案
你不能如果在一端使用writeUTF()
,则必须在另一端使用readUTF()
。
您只需确定要使用的API,而不必尝试将它们混合使用。
关于java - 如何使用BufferedReader读取DataInputStream中的内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31672179/