简体   繁体   English

如何与Java中的虚拟机通信?

[英]How to communicate with a Virtual Machine in Java?

I have made a little Java program that asks a person to enter a pin code. 我制作了一个小的Java程序,要求人们输入密码。 As soon as the pin code is entered, it reads into a "bdd.txt" file in which all the pins are stored and then it displays :) if good and :( if wrong. Simple application so far. 输入密码后,它将读入一个“ bdd.txt”文件,其中存储了所有引脚,然后显示:)(如果良好)和:(如果错误。到目前为止,很简单的应用程序。

What I want to do is to move that "database" file into a Virtual Machine on my computer (such as Ubuntu for example), and then do the same thing. 我想要做的是将“数据库”文件移到计算机上的虚拟机(例如Ubuntu)中,然后执行相同的操作。 This way, it won't be local anymore, since the file will not be located at the root of my project anymore. 这样,它将不再是本地的,因为该文件将不再位于我项目的根目录下。

Here is what my application looks like : 这是我的应用程序的外观:

输入好的密码3个错误的插针后

As you can see, the app starts, the user is asked to enter is pin code. 如您所见,该应用程序启动,要求用户输入密码。 If this is a good one, the app is done, if not he has 2 more tries left until the app stops. 如果这是一个好的选择,则应用程序完成,否则,他还有2次尝试,直到应用程序停止。

When the pin is entered, my program checks in "bdd.txt" if the pin is there or not. 输入图钉后,我的程序会在“ bdd.txt”中检查图钉是否存在。 It plays the database role: 它扮演数据库角色:

bdd.txt

To understand what I need, it is necessary to assimilate this program to something that needs to be secure. 要了解我的需求,有必要将该程序吸收到需要安全的内容中。 We do not want the pins database at the same place as the program (or the device in real life). 我们不希望引脚数据库与程序(或现实生活中的设备)位于同一位置。 So we put it on a Virtual Machine and we have to communicate between my Windows7 Java program in Eclipse and the bdd.txt file on VMWare Player's Ubuntu. 因此,我们将其放在虚拟机上,并且必须在Eclipse中的Windows7 Java程序与VMWare Player的Ubuntu上的bdd.txt文件之间进行通信。

My question is how is that possible ? 我的问题是怎么可能? How do I need to change my code to let my program reach something on my VM ? 我如何更改代码以使程序到达VM上的某些内容? Is there a specifig technology I should use for it ? 我应该使用一种特定的技术吗? Do I need to do some configurations first ? 我需要首先进行一些配置吗?

Here is my code : 这是我的代码:

import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.*;

public class Main extends JFrame {

    private static final long serialVersionUID = 1L;

    private JPanel container = new JPanel();
    private JPasswordField p1 = new JPasswordField(4);
    private JLabel label = new JLabel("Enter Pin: ");
    private JButton b = new JButton("OK");


    public Main() {
        this.setTitle("NEEDS");
        this.setSize(300, 500);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);

        container.setBackground(Color.white);
        container.setLayout(new BorderLayout());
        container.add(p1);
        JPanel top = new JPanel();

        PlainDocument document =(PlainDocument)p1.getDocument();

        b.addActionListener(new BoutonListener());

        top.add(label);
        top.add(p1);
        p1.setEchoChar('*');
        top.add(b);  

        document.setDocumentFilter(new DocumentFilter(){

            @Override
            public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                String string =fb.getDocument().getText(0, fb.getDocument().getLength())+text;

                if(string.length() <= 4)
                super.replace(fb, offset, length, text, attrs); //To change body of generated methods, choose Tools | Templates.
            }
        });


        this.setContentPane(top);
        this.setVisible(true);
    }

    class BoutonListener implements ActionListener {
        private final AtomicInteger nbTry = new AtomicInteger(0);
        ArrayList<Integer> pins = readPinsData(new File("bdd.txt"));

        @SuppressWarnings("deprecation")
        public void actionPerformed(ActionEvent e) {
            if (nbTry.get() > 2) {
                JOptionPane.showMessageDialog(null,
                        "Pin blocked due to 3 wrong tries");
                return;
            }
            final String passEntered=p1.getText().replaceAll("\u00A0", "");
            if (passEntered.length() != 4) {
                JOptionPane.showMessageDialog(null, "Pin must be 4 digits");
                return;
            }
            //JOptionPane.showMessageDialog(null, "Checking...");
            //System.out.println("Checking...");
            SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    boolean authenticated = false;

                    if (pins.contains(Integer.parseInt(passEntered))) {
                        JOptionPane.showMessageDialog(null, ":)");
                        authenticated = true;
                    }

                    if (!authenticated) {
                        JOptionPane.showMessageDialog(null, ":(");
                        nbTry.incrementAndGet();
                    }
                    return null;
                }
            };
            worker.execute();
        }

    }

    //Function to read/access my bdd.txt file
    static public ArrayList<Integer> readPinsData(File dataFile) {
        final ArrayList<Integer> data=new ArrayList<Integer>();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(dataFile));
            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    try {
                        data.add(Integer.parseInt(line));
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        System.err.printf("error parsing line '%s'\n", line);
                    }
                }
            } finally {
                reader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("error:"+e.getMessage());
        }

        return data;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Main();
            }
        });

    }
}

Any ideas ? 有任何想法吗 ? Thanks, 谢谢,

Florent. 弗洛朗。

A shared folder will certainly work, but there seems little point in having a VM at all, because the PIN file is also on your host machine, and java is reading it directly. 共享文件夹当然可以工作,但是拥有VM似乎毫无意义,因为PIN文件也位于您的主机上,并且Java正在直接读取它。

Maybe you need a client/server architecture? 也许您需要客户端/服务器架构?

You program with the UI will be the client. 您使用UI进行编程将是客户端。 The client will be configured with a means of calling the server (IP address and port). 将为客户端配置一种调用服务器的方式(IP地址和端口)。 The client does not have access to the bdd.txt file, but the server does. 客户端无权访问bdd.txt文件,但服务器具有访问权。

On your VM, you have another java application, the Server. 在您的VM上,您还有另一个Java应用程序,即服务器。 Your server listens for requests from the client. 您的服务器侦听来自客户端的请求。 The request will contain a PIN entered by the user. 该请求将包含用户输入的PIN。 The server then checks it against the PINs in the file, and responds with a yes or no. 然后,服务器根据文件中的PIN对其进行检查,并以是或否做出响应。 Your client receives the yes/no response from the server, and reports the result back to the user. 您的客户端从服务器收到是/否响应,并将结果报告给用户。

Read about Sockets programming here to get started 在这里阅读有关套接字编程的入门

There are two things you would need to do: 您需要做两件事:

  1. Share a folder between your host OS and your VM. 在主机操作系统和VM之间共享文件夹。 This will allow your Virtual Machine to access files from the host operating system. 这将使您的虚拟机可以从主机操作系统访问文件。 You would want to put your pin file in this folder. 您可能希望将PIN文件放在此文件夹中。
  2. Have your application read the pin file from the shared folder. 让您的应用程序从共享文件夹中读取Pin文件。 This would mean changing this line: 这意味着更改此行:

    ArrayList<Integer> pins = readPinsData(new File("bdd.txt"));

    Right now, this code is reading the file bdd.txt from the current directory the user is in, which I assume is the directory your executable is in. Instead, you want this to point to the pin file in your shared directory. 现在,此代码正在从用户所在的当前目录中读取文件bdd.txt,我认为这是可执行文件所在的目录。相反,您希望它指向共享目录中的pin文件。 To make your code as flexible as possible, you may want to pass in the path to the pin file as a command line argument when you start the program. 为了使代码尽可能灵活,启动程序时,您可能希望将命令行文件的路径作为命令行参数传递。

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

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