首页 > 解决方案 > 这个 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);
            }
        }
    }
}

输出

标签: javasockets

解决方案


in.read等待直到有一些数据要读取,或者服务器关闭连接。(如果服务器关闭连接,则返回 0)

由于服务器不再发送任何数据,也没有关闭连接,它会永远等待。

您需要这样做,以便服务器在发送所有数据后关闭连接,或者服务器有其他方式告诉客户端何时完成发送所有数据(例如,通过发送总字节数然后发送客户端读取正确的字节数后停止)。


推荐阅读