目标:将数据发送到服务器并让服务器返回一些内容并打印服务器发回的内容
问题:如果我关闭输出流,它会将数据发送到服务器,但我的输入流不起作用,我无法接收服务器试图给我的内容。如果我使用 flush() 将数据发送到服务器,则服务器永远不会收到数据。我已经坚持了3个小时。你如何同时阅读和写作。
客户端.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
class Client {
public static void main(String args[]) {
String data = "head";
try {
Socket skt = new Socket("server", 5050);
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
out.print(data);
out.close();
System.out.println("Sent data");
while (!in.ready()) {
}
String input = in.readLine();
System.out.println(input);
out.close();
in.close();
skt.close();
} catch (Exception e) {
System.out.print("Whoops! It didn't work!\n" +e.toString());
}
}
}
服务器.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.PrintWriter;
class Server {
public static void main(String args[]) {
String data;
String input;
try {
ServerSocket srvr = new ServerSocket(5050);
Socket skt = srvr.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
skt.getInputStream()));
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
// /////Waits for message from client/////////
while (!in.ready()) {
}
// ///////////////////////////////////////////
input = in.readLine(); // Read the message
System.out.println("Received String input: " + input);
// Send output to client
System.out.println("After output");
if (input.equals("head"))
data = "haha";
else
data = "Wtf did you send me";
Thread.sleep(2000);
out.print(data);
// ///////////////////
System.out.println("Sent data: " + data);
in.close();
out.close();
skt.close();
srvr.close();
} catch (Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}