我编写了一个简单的java代码,用于从服务器向客户端发送消息,客户端应分别显示它。 代码是。
Client.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
Socket client_socket = new Socket("localhost", 1235);
BufferedReader reader = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client_socket.getOutputStream()));
String serverMsg = null;
while ((serverMsg = reader.readLine()) != null) {
System.out.println("Client: " + serverMsg);
}
}
}
Server.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket server_socket;
server_socket = new ServerSocket(1235);
while (true) {
Socket mysocket = server_socket.accept();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(mysocket.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(mysocket.getInputStream()));
writer.write("Hello omkar ");
System.out.println("data sent");
}
}
}
问题: 现在的问题是,当我运行这些代码时,我得到服务器端发送的消息数据,但客户端控制台是空白的。请帮我找出错误。
答案 0 :(得分:3)
在服务器代码中而不是使用BufferedWriter,请使用PrintWriter。
while (true) {
Socket mysocket = server_socket.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(mysocket.getInputStream()));
out.println("Hello World!");
System.out.println("data sent");
}
这适用于我的系统。试试这个。
答案 1 :(得分:2)
你正在读行,但你不是在写行。在邮件中添加行终止符,或使用newline()
。