我正在创建一个服务器和一个客户端。现在我可以从 向 发送消息Client
,ServerThread
并且ServerThread
能够得到消息。但是当ServerThread
尝试回复时,Client
没有得到响应,但消息已发送。似乎它正在等待响应,但永远无法收到它。
服务器线程:
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();
}
}