java - 这个 Java 程序在哪里卡住了?
问题描述
我正在编写一个 Java 客户端,它向服务器发送消息并接收相应的音频(文本到语音)作为字节流。我成功地在“缓存”目录中找到了音频,但我的程序只是挂起而没有结束。它在“receiveAudio”方法中进入 while 循环,并在标准输出中打印消息的长度。如果它被卡在 while 我期望无限打印,但它只打印一次。此外,它不会退出,因为如果它退出,我会在输出中得到“完成时”。我不明白发生了什么事。我很少使用 java,所以我可能犯了一些愚蠢的错误。在我得到的代码和输出屏幕下方。
public class Main {
public static void main(String[] args) {
String msg = "I don't know what to say";
ConnectionThread c = new ConnectionThread(msg);
c.start();
}
private static class ConnectionThread extends Thread {
private String msg;
ConnectionThread(String msg) {
this.msg = msg;
}
@Override
public void run() {
try {
Socket s = new Socket("127.0.0.1", 1234);
PrintWriter pr = new PrintWriter(s.getOutputStream(), true);
pr.print(msg);
pr.flush();
receiveAudio(s);
s.close();
System.out.println("Run finished");
} catch (Exception e){
e.printStackTrace();
System.out.println(e);
}
}
private void receiveAudio(Socket s) throws IOException {
DataInputStream in = new DataInputStream(new BufferedInputStream(s.getInputStream()));
byte[] msgByte = new byte[1000000];
int totBytes = 0;
boolean end = false;
try {
File dstFile = new File("cache/audio.wav");
FileOutputStream out = new FileOutputStream(dstFile);
int len;
while ((len = in.read(msgByte)) > 0) {
System.out.println(len);
out.write(msgByte, 0, len);
}
System.out.println("while finished");
out.close();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println(ex);
}
}
}
}
解决方案
in.read
等待直到有一些数据要读取,或者服务器关闭连接。(如果服务器关闭连接,则返回 0)
由于服务器不再发送任何数据,也没有关闭连接,它会永远等待。
您需要这样做,以便服务器在发送所有数据后关闭连接,或者服务器有其他方式告诉客户端何时完成发送所有数据(例如,通过发送总字节数然后发送客户端读取正确的字节数后停止)。
推荐阅读
- ansible - 如何使用 ansible 从 yaml 文件中获取自定义列表?
- angular - 角度显示这种类型的错误我如何解决这个问题?
- json - 如何按条件选择最大值然后与其他值进行比较?
- kotlin - Kotlin:防止混淆相同类型的参数
- wordpress - 在 WordPress 中按产品按钮过滤产品
- javascript - 如何根据javascript中的滚动位置动态更改div的高度?
- android - Youtube Data API 快速入门代码始终运行取消功能
- python - Pandas 高级问题:对于每一行,从另一个数据框中获取复杂信息
- matrix - Julia - 如何有效地将矩阵的对角线归零?
- javascript - 如何从 Google 地球引擎下载特定多边形的哨兵 1