java - DataInputStream readLong() 得到错误的值

标签 java sockets datainputstream dataoutputstream

您好,我在使用 DataInputStream 的 readLong() 方法时遇到了一些问题。 当我通过 DataOutputStream.writeLong() 它是正确的值,但是当它被发送时它比它应该的大很多,我把代码都放在一个可运行的语句中,这样程序就不会卡住

这是客户

    socket = new Socket(ipAddress, Port);

    bos = new BufferedOutputStream(socket.getOutputStream());
    dos = new DataOutputStream(bos);

    File f = new File("C:/Users/lukeLaptop/Downloads/RemoveWAT22.zip");

    long length = f.length();
    dos.writeLong(length);

    String name = f.getName();
    dos.writeUTF(name);

    FileInputStream fis = new FileInputStream(f);
    bis = new BufferedInputStream(fis);

    int theByte = 0;
    while ((theByte = bis.read()) != -1) {
        bos.write(theByte);
    }
    bis.close();

    dos.close();

服务器端

    ServerSocket server = new ServerSocket(8080);

    while (true) {
        socket = server.accept();

        System.out.println("Got a client !");

        bis = new BufferedInputStream(socket.getInputStream());

        dis = new DataInputStream(bis);

        int filesCount = dis.readInt();



        long fileLength = dis.readLong();
        //String fileName = dis.readUTF();

        File f = new File("C:/test/here/test.zip");

        FileOutputStream fos = new FileOutputStream(f);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        for (int j = 0; j < fileLength; j++) {
            bos.write(bis.read());
        }

        bos.close();
        dis.close();

编辑

如果有人可以帮助我编写代码,我将不胜感激并使用 writeUTF 发送名称,但我不知道发生了什么以及如何解决它

最佳答案

问题是方法writeUTF

javadoc说:

Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.

First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the modified UTF-8 encoding for the character. If no exception is thrown, the counter written is incremented by the total number of bytes written to the output stream. This will be at least two plus the length of str, and at most two plus thrice the length of str.

但是您使用自己的长度编码,它只需要字符串包含的字符数。它不使用字符串的编码长度。

如果使用 DataInputStream.readUTF(),则不必使用自己的长度编码阅读你的字符串。

关于java - DataInputStream readLong() 得到错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21840587/

相关文章:

ruby-on-rails - 如何在 Rails 应用程序中实现 TCP 套接字?

C++ 套接字无法正常工作

java - 无法将数据输入到数据输出流

Java BufferedInputStream.read() IndexOutOfBounds

java - 生成 3000 字节的随机字符串

java - JodaTime:使用特定间隔获取两个日期之间的日期

java - 邮件触发时出错

android - 在 `adb forward` 和 `usbmuxd` 的情况下,谁应该是 socket 服务器,谁应该是客户端

java - DataInputStream接收不准确

java - Java 将子数组复制到已初始化数组的方法