我是socket編程新手。我必須編寫一個程序,其中客戶端接受用戶的文件名並將其發送到服務器。服務器讀取相應的文件並將其內容發送回客戶端。現在我的問題是服務器程序凍結'String file = br.readLine()'。當我終止我的客戶端程序時,會執行更多的服務器代碼。如果我在客戶端代碼的末尾註釋掉while循環,則服務器代碼完美無缺(將數據打印到標準輸出)。你能告訴我的代碼有什麼問題嗎? 服務器代碼:爲什麼服務器程序在線上凍結'String file = br.readLine()'?
public class SocketServer {
public static void main(String[] args) throws Exception{
System.out.println("Server is started.");
ServerSocket ss = new ServerSocket(9999);
System.out.println("Server is waiting for a client.");
Socket server = ss.accept();
System.out.println("Client is connected.");
BufferedReader br = new BufferedReader(new InputStreamReader(server.getInputStream()));
String file = br.readLine();
System.out.println("Requested file is: " + file);
OutputStreamWriter os = new OutputStreamWriter(server.getOutputStream());
PrintWriter writer = new PrintWriter(os);
BufferedReader fr = new BufferedReader(new FileReader(file));
String line;
while((line = fr.readLine()) != null) {
writer.write(line);
writer.flush();
System.out.println(line);
}
}
}
客戶端代碼:
public class SocketClient {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
Socket client = new Socket("localhost", 9999);
OutputStreamWriter os = new OutputStreamWriter(client.getOutputStream());
PrintWriter writer = new PrintWriter(os);
System.out.print("Enter filename: ");
String file = in.nextLine();
writer.write(file);
writer.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("Content of " + file + ":");
String str;
while((str = br.readLine()) != null) {
System.out.print(str);
}
System.out.println("File transfer is complete.");
}
}
您需要一個調試器。 – notyou
我使用了一個調試器。它向我展示了服務器程序凍結的路線。 –