java 服务器上的 readInt() 没有得到好的 int

java readInt() on server doesn't get the good int

我正在实施一个 "little" client/server 应用程序,就像一个 Cloud。 问题是:我是 Java 的新手。 所以我学得有点快,client/server 通信、数据库、框架、线程也是如此。

我很确定我的代码不会是最好的,但事实是:我必须使用 Java,而且我必须快速完成。我不会尝试优化它,我只需要它工作。

我已经实现了很多,所以我不会在这里给出所有代码,只是解释一下我的问题之前发生了什么: 客户端的主编打开一个登录框架。客户可以注册或登录。注册运行良好,假设他登录了。如果身份验证有效,则会打开另一个框架,其中包含 "browse" 和 "upload" 选项。这个想法是,他浏览一个文件然后上传它。当他点击上传时,它应该调用上传函数,该函数将一个 byte[2] 数组和一个 DataOutputStream 对象一起发送到服务器。 (它首先发送数组的大小,然后发送数组)

在服务器端,当身份验证有效时,它会将客户端套接字提供给 "Cloud" class,它 - 到现在 - 只是应该接收一个字节数组(它'稍后我会做更多,但现在我无法获得这个字节数组)

但是服务器收到的大小是 1970302063 而不是 2。我已经检查了客户端大小 writeInt 之前的大小,它是 2。在服务器端的 readInt 之后,它是1970302063.

我不明白。服务器可以在某处接收其他东西,而我漂亮的 2 丢失在缓冲区中吗?

服务器端:

public class Server {

    public static void main(String[] zero) throws IOException {

        ServerSocket serverSocket  ;
        Socket clientSocket ;
        int tmp = 0; //when everything works, tmp will disappear

        DataBase DB = new DataBase();
        System.out.println("ouverture du server");
        serverSocket = new ServerSocket(2017);


        while(tmp<1) { //limit the number of connections allowed.
            try {

                clientSocket = serverSocket.accept(); 
                Thread t = new Thread(new Connect(clientSocket, DB));
                t.start();

                //clients.printAll(); //just to see the DB.

            }catch (IOException e) {
                e.printStackTrace();
            }
            tmp++;      
        }    
        serverSocket.close();
    }
}

如您所见,我只授权了 1 个连接,因为我仍在测试它并且我不想每次遇到错误/更改某些内容时都更改端口号。有了它,我只需要在每次测试后重新启动服务器。

public class Connect implements Runnable{
    private DataBase DB;
    private Socket clientSocket;

    public Connect(Socket socket, DataBase DB) {
        this.clientSocket = socket;
        this.DB = DB;
    }

    public void run() {
        try {
            BufferedReader in;
            PrintWriter out;
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            out = new PrintWriter(clientSocket.getOutputStream());
            String mode = in.readLine();
            String clientID = in.readLine();
            String clientPwd = in.readLine();
            if (mode.equals("auth")) {
                Authentification auth = new Authentification (clientID, clientPwd, DB);
                out.write(auth.getMessage()+"\r\n");
                out.flush();
                if (auth.getMessage().equals("Login Successfull. Welcome in SecureCloud!"))
                    new Cloud(clientSocket, DB);    //launch Cloud.
            }
            else if (mode.equals("reg")) {
                Registration reg= new Registration(clientID, clientPwd, DB);
                out.write(reg.getMessage()+"\r\n");
                out.flush();
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            this.clientSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

现在,这里:身份验证和注册将建立连接,最后关闭客户端套接字。但是,如果身份验证成功,则会创建一个新的云:

public class Cloud {
    public Cloud(Socket clientSocket, DataBase DB) {
        try {
            DataInputStream dIn = new DataInputStream(clientSocket.getInputStream());
            int length = dIn.readInt();                    // read length of incoming message
            System.out.println("byte array size: "+length);
            byte[] shorthash;
            if(length!=2) {
                System.err.println("Incorrect size for shorthash!");
            }

            else {
                shorthash = new byte[length];
                dIn.readFully(shorthash, 0, shorthash.length); // read the message
                System.out.println(shorthash);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

如您所见,目前它的作用不大。我知道我必须添加一个 while(true) 循环以便客户端可以上传更多文件,但现在如果我可以只发送这个字节数组我会很高兴。

现在,客户端。我将跳过 main,它只是打开登录框架。我还将跳过大部分登录框架,它只是一个框架...这是客户端单击 "login" 时发生的情况:

public  void    actionPerformed(ActionEvent e)
{ 
    if  (e.getSource()==connectButton) {
        Connection con = new Connection();
        con.auth(username.getText(), password.getText());
        if(con.getServerAnswer().equals("Login Successfull. Welcome in SecureCloud!")) {
            this.setVisible(false);
            con.setConnection(true);
            con.setUsername(username.getText());
            new Load_Frame(con.getUsername(),con.getSocket());
        }
        else System.out.println("erreur: " + con.getServerAnswer());
    }
    else if (e.getSource()==registerButton) {
        this.setVisible(false);
        new Registration_Frame();
    }
}

因此,它会创建连接并使用用户名和密码启动身份验证过程 (con.auth)。如果成功,它将使用用于此连接的用户名和套接字打开负载框架。 我将再次跳过 Load Frame 的大部分内容,这里是操作:

public  void    actionPerformed(ActionEvent e)
{ 
    if  (e.getSource()== uploadButton) {
        this.filename = uploadField.getText();
        File file = new File(filename);
        //TODO: change the upload function:
        try {
            client.upload(file);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    else if (e.getSource()== downloadButton) {
        this.filename = downloadField.getText();
        //TODO: change the download function
        //download(filename);
    }

    else if (e.getSource()== browseButton) {
        JFileChooser jc = new JFileChooser();
        if(jc.showOpenDialog(this) != 1)
            uploadField.setText(jc.getSelectedFile().getAbsolutePath());
    }
}

最后但同样重要的是,"upload" 函数,由 client.upload(file):

调用
public void upload(File originalFile) throws NoSuchAlgorithmException, NoSuchPaddingException, IOException {

    //create the "FileData" object, which make the shorthash of the file.
    FileData myfile = new FileData(originalFile, fileID);

    //say to the server that we want to upload:
    PrintWriter mode;
    mode = new PrintWriter(socket.getOutputStream());
    mode.println("upload");
    mode.flush();

    //Send shorthash to the server:
    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
    System.out.println("byte array size: "+myfile.shortHash.length);
    out.writeInt(myfile.shortHash.length); // send the length of the byte array
    //out.flush();
    out.write(myfile.shortHash);  //send the array

}

我试过使用和不使用 out.flush(),都没有任何区别。

综上所述,这是我得到的答案: 来自客户:

Asking for authentification...
Login Successfull. Welcome in SecureCloud!
No file uploaded
byte array size: 2

来自服务器:

Connection to SQLite has been established.
ouverture du server
byte array size: 1970302063
Incorrect size for shorthash!

当然,因为我知道字节数组的大小,我可以很容易地告诉服务器"hey, the size is 2!"(我的意思是,直接用新字节[2]初始化我的数组) 但我想了解这里发生了什么。另外,如果我没有收到合适的尺寸,也许我不会收到好的阵列。

所以,感谢那些真正快速发现问题的人:) 这有点愚蠢,即使你重读你的代码 5 次你也看不到这种问题,但是其他人读了它他会在一分钟内看到它。

解决方法是在上传功能中删除这部分:

//say to the server that we want to upload:
PrintWriter mode;
mode = new PrintWriter(socket.getOutputStream());
mode.println("upload");
mode.flush();

在我更改服务器端的代码之前它很有用,现在它很烦人^^