我有一个问题从我已经实现的代码获取我想要的输出以创建服务器/客户端程序...它只是一个非常简单的,我不知道为什么我不得到我想要的东西。
以下是服务器的代码:
ServerSocket serverSocket = new ServerSocket(1025);
System.out.println("Porting...");
Socket socket = serverSocket.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String s = in.readLine();
System.out.println("Server read: " + s);
out.write("Got it");
socket.close();
System.out.println("Server Exit");
客户:
System.out.print("Connecting...");
Socket socket = new Socket("localhost",1025);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.write("Hello, Server");
String s = in.readLine();
System.out.println("Client Recieved: " + s);
socket.close();
System.out.println("Client Exit");
我尝试获取Hello,Server输出,而不是从客户端获取“连接”syso(我刚才看看它是否有效)
答案 0 :(得分:0)
在流上写入后,您必须通过在输出流上调用flush()方法来刷新流。否则,一旦流缓冲区已满,将刷新流。
out.flush();
此外,您必须确保输入新行字符以提及行尾。因为readLine()用newline()等待字符串。
A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r')
out.write("Hello, Server\n");
out.flush();