gpt4 book ai didi

java - 为什么服务器程序在 'String file = br.readLine()' 行卡住?

转载 作者:行者123 更新时间:2023-12-01 20:12:00 25 4
gpt4 key购买 nike

我是套接字编程新手。我必须编写一个程序,其中客户端接受用户的文件名并将其发送到服务器。服务器读取相应的文件并将其内容发送回客户端。现在我的问题是服务器程序卡住在“String file = br.readLine()”上。当我终止客户端程序时,将执行更多的服务器代码行。如果我在客户端代码末尾注释掉 while 循环,则服务器代码工作得很好(它将数据打印到标准输出)。你能告诉我我的代码有什么问题吗?服务器代码:

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.");
}

}

最佳答案

br.readLine(); 将等待输入,直到找到换行符。

writer.write(file); 您正在写入不带换行符的文件名。

因此,为了使其正常工作,要么在客户端写入换行符,要么在服务器上逐个字符地读取它。

希望这有帮助。

关于java - 为什么服务器程序在 'String file = br.readLine()' 行卡住?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46570133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com