繁体   English   中英

无法从Android上的套接字打开接收到的amr / jgp文件

[英]Can't open received amr/jgp file from socket on android

为了通过Wifi通过套接字发送和接收文件,我使用了以下代码...

客户端 :

Socket socket = new Socket(dstAddress, dstPort);
            int bufferSize=socket.getReceiveBufferSize();
            InputStream in=socket.getInputStream();
            DataInputStream clientData = new DataInputStream(in);
            String fileName = clientData.readUTF();
            System.out.println(fileName);
            OutputStream output = new FileOutputStream("/sdcard/"+fileName);

            byte[] buffer = new byte[bufferSize];
            int read;
            while((read = clientData.read(buffer)) != -1){
                output.write(buffer, 0, read);
            }


            //close every thing
            output.flush();
            output.close();
            socket.close();

服务器端:

File file = new File(Environment.getExternalStorageDirectory(), "/sdcard/test.amr");

            byte[] mybytearray = new byte[8092];
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            DataInputStream dis = new DataInputStream(bis);
            OutputStream os;
            try {
                os = socket.getOutputStream();
                DataOutputStream dos = new DataOutputStream(os);
                dos.writeUTF(file.getName());
                dos.writeLong(mybytearray.length);
                int read;
                while((read = dis.read(mybytearray)) != -1){
                    dos.write(mybytearray, 0, read);

                }
                os.flush();

                os.close();
                socket.close();

此时,我正在从服务器接收文件“ test.amr”,而没有更改其原始大小。 但是,当我尝试在客户端设备中播放文件时,无法播放。

注意:使用上述代码接收的mp3,avi和txt文件可以打开并完美播放。

请建议如何解决此问题。

最后,我通过删除dos.writeLong(mybytearray.length);解决了上述问题。 线形服务器代码...根据greenapps的建议。

我修改后的服务器代码是:

File file = new File(Environment.getExternalStorageDirectory(), "/sdcard/test.amr");

        byte[] mybytearray = new byte[8092];
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        DataInputStream dis = new DataInputStream(bis);
        OutputStream os;
        try {
            os = socket.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(file.getName());
            int read;
            while((read = dis.read(mybytearray)) != -1){
                dos.write(mybytearray, 0, read);

            }
            os.flush();

            os.close();
            socket.close();

您正在写long的缓冲区大小,但没有读取它。 因此, long作为图像的一部分被读取。 由于写入发送缓冲区的大小与接收者没有任何关联,因此应从发送者中删除writeLong(mybytearray.length)调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM