【发布时间】:2021-02-28 12:56:54
【问题描述】:
我正在编写一个 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);
}
}
}
}
【问题讨论】:
-
检查this answer。它可能具有相关性。
-
调用
in.read卡住了,因为in.read一直等到有一些数据。 -
您可以通过获取线程转储找出程序卡在哪里。您可以使用
jstack <pid>命令来执行此操作,其中<pid>是您的JVM 的进程ID。