我正在创建一个服务器和一个客户端。现在,我可以从Client
向ServerThread
发送消息,ServerThread
能够收到消息。但是当ServerThread
尝试回复时,Client
没有收到回复,但邮件已发送。它似乎在等待响应,但永远无法接收它。
ServerThread:
public class ServerThread extends Thread {
private Socket socket;
private DataOutputStream outToClient;
private BufferedReader inFromClient;
public ServerThread(Socket socket) {
try {
System.out.println("Thread started");
this.socket = socket;
outToClient = new DataOutputStream(socket.getOutputStream());
inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
System.out.println("Thread running");
try {
System.out.println("ServerThread: " + inFromClient.readLine());
outToClient.writeBytes("I Can help you");
} catch (Exception e) {
e.printStackTrace();
}
}
}
服务器:
public class Server {
public static final int PORT = 5589;
public static void main(String[] args) {
ServerSocket socket;
try {
socket = new ServerSocket(5589);
while (true)
new ServerThread(socket.accept()).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端:
public class Client {
public static void main(String args[]) throws Exception {
Socket socket = new Socket("localhost", App.PORT);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter outToServer = new PrintWriter(socket.getOutputStream(), true);
outToServer.println("Hello, I'm Lost");
System.out.println(inFromServer.readLine()); //Hangs on this line
socket.close();
}
}
答案 0 :(得分:2)
您的数据在服务器端缓冲,并且在缓冲区已满之前不会自动发送:您.flush()
之后应该在服务器端.writeBytes()
确保它被发送,即使您没有发送达不到缓冲区大小(这取决于操作系统和套接字配置)。