如何通过套接字Java传输数据

时间:2015-06-12 16:45:30

标签: java android sockets

我尝试在android上直接发送带wifi的文件,但只发送和接收文件名..我从这里按照代码Large file transfer over java socket
这是我的代码
发件人

2015-06-12 23:00:00 +0000


接收机

Socket socket = new Socket();
        int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;
        OutputStream os = null;
        DataOutputStream dos = null;
        try {
            //socket.bind(null);
            socket.connect((new InetSocketAddress("192.168.49.1", port)), SOCKET_TIMEOUT);
            ContentResolver cr = context.getContentResolver();
            Uri uri = null;
            uri = uri.parse(FileUri);
            File myFile = new File(uri.getPath());
            byte[] mybytesarray = new byte[(int) myFile.length()];
            fis = new FileInputStream(myFile);
            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);
            dis.readFully(mybytesarray, 0, mybytesarray.length);
            os = socket.getOutputStream();
            dos = new DataOutputStream(os);
            dos.writeUTF(myFile.getName()); //write fileName
            dos.writeLong(mybytesarray.length); //write file length/size
            int read;
            while ((read = dis.read(mybytesarray)) > 0) {
                dos.write(mybytesarray, 0, read); 
            }
        } catch (IOException e) {
                Log.e(WiFiDirectActivity.TAG, e.getMessage());
            } finally {
            if (socket != null) {
                if (socket.isConnected()) {
                    try {
                        dos.close();
                        os.close();
                        dos.close();
                        socket.close();
                        Log.d(WiFiDirectActivity.TAG, "socket close");
                    } catch (IOException e) {
                        // Give up
                        e.printStackTrace();
                    } 

1 个答案:

答案 0 :(得分:1)

            while ((read = dis.read(mybytearray)) > 0) {
                dos.write(mybytearray, 0, mybytearray.length);
                Log.d(WiFiDirectActivity.TAG, "sending");
                dos.flush();
            }

        long size = ClientData.readLong();
        byte[] buffer = new byte[1024];
        while((size = ClientData.read(buffer)) > 0){
            output.write(buffer, 0, bytesRead);
            size = bytesRead;
        }

您已经破坏了此代码,并且在链接的问题中使用了错误的答案:请参阅我的众多评论。它应该是:

            while ((read = dis.read(mybytearray)) > 0) {
                dos.write(mybytearray, 0, read);
                Log.d(WiFiDirectActivity.TAG, "sending");
            }

(永远不要在循环内冲洗)和

        long size = ClientData.readLong();
        byte[] buffer = new byte[8192]; // at least
        int bytesRead;
        while((bytesRead = ClientData.read(buffer)) > 0){
            output.write(buffer, 0, bytesRead);
        }