Передача ввода клиента в класс, связанный с классом сервера - PullRequest
1 голос
/ 19 апреля 2020

Я работаю над приложением клиент-сервер, чтобы получить строку ввода от пользователя и вывести, сколько раз эта последовательность была найдена в файле. Класс, который читает файл и считает последовательность, является отдельным классом, который я пытаюсь подключить к классу сервера, поэтому входные данные от пользователя передаются на сервер, который передает его этому классу, а затем возвращает выходные данные клиент ... но я не знаю как, пожалуйста, помогите!

Класс клиента

public class Client extends JFrame {

    private JTextField userText;
    private JTextArea chatWindow;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private String message = "";
    private String serverIP;
    private Socket connection;


    //constructor
    public Client(String host) {
        super("Client ...");
        serverIP = host;
        userText = new JTextField();
        userText.setEditable(false);
        userText.addActionListener(
                new ActionListener() {
                    public void actionPerformed (ActionEvent event) {
                        sendMessage(event.getActionCommand());
                        userText.setText("");
                    }
                });
        add(userText, BorderLayout.NORTH);
        chatWindow = new JTextArea();
        add(new JScrollPane(chatWindow), BorderLayout.CENTER);
        setSize(400,150);
        setVisible(true);
    }

    //connect to server
    public void startRunning() {
        try {
            connectToServer();
            setupStreams();
            whileChatting();
        }catch(EOFException eofException) {
            showMessage("Client terminated connection\n");
        }catch(IOException ioException) {
            ioException.printStackTrace();
        }finally {
            closeEverything();
        }
    }

    //connecting to the server for reals
    private void connectToServer() throws IOException{
        showMessage("Trying to connect....");
        connection = new Socket(InetAddress.getByName(serverIP), 6789);
        showMessage("Finally connected to: " + connection.getInetAddress().getHostName());
    }

    //setting up to transmit information
    private void setupStreams() throws IOException{
        output = new ObjectOutputStream(connection.getOutputStream());
        output.flush();
        input = new ObjectInputStream(connection.getInputStream());
        showMessage("\n DNA searching is now live \n");
    }

    //private void whileChatting
    private void whileChatting() throws IOException{
        ableToType(true);

        do{
            try {
                message = (String) input.readObject();
                showMessage("\n" + message);
            }catch(ClassNotFoundException classNotFoundException) {
                showMessage("\n I do not recognize your input\n");
            }
        }while(!message.equals("SERVER-END"));
    }

    //Time to close the streams, and sockets
    private void closeEverything(){
        showMessage("\n Closing connection...");
        ableToType(false);
        try {
            output.close();
            input.close();
            connection.close();
        }catch(IOException ioException) {
            ioException.printStackTrace();
        }
    }

    //Communicate with the server\
    private void sendMessage(String message) {
        try {
            output.writeObject("CLIENT - " +message);
            output.flush();
            showMessage("\nCLIENT - "+message);
    }catch(IOException ioException) {
        chatWindow.append("\n Error string not sent.."); 
        } 
    }

    //update display
    private void showMessage(final String m) {
        SwingUtilities.invokeLater(
                new Runnable() {
                    public void run() {
                        chatWindow.append(m);
                    }
                }

        );
    }

    //Allow user search for chromosomes

    private void ableToType (final boolean tof) {
        SwingUtilities.invokeLater(
                new Runnable() {
                    public void run() {
                        userText.setEditable(tof);
                    }
                }

        );

    }
}

Класс сервера

public class Server extends JFrame {

    private JTextField userText;
    private JTextArea chatWindow;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private ServerSocket server;
    private Socket connection;
    GenomeSearcher Gs = new GenomeSearcher();
    String findSequence, chromosome;

    //constructor

    public Server() {
        super("DNA Strands Search Engine");
        userText = new JTextField();
        userText.setEditable(false);
        userText.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                //pass the genetic code function here!
                sendMessage(event.getActionCommand());
                userText.setText("");
                //end user text here



            }

        });    //end action listener

        add(userText, BorderLayout.NORTH);
        chatWindow = new JTextArea();
        add(new JScrollPane(chatWindow));
        setSize(400, 150);
        setVisible(true);


        userText.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e) {
                runSearcher();
                sendMessage(e.getActionCommand());
            }
        }


        );


    }//end server

    public void runSearcher() {
        Gs.countSequence(findSequence, chromosome);
    }

        //set up and run server
        public void startRunning() {
            try {
                server = new ServerSocket(6789, 100);
                while(true) {
                    try {
                        waitForConnection();
                        setupStreams();
                        whileChatting(); //might not need this
                    }catch(EOFException eofException) {
                        showMessage("\n Server closed the connection...");
                    }finally {
                        closeEverything();
                    }
                }//end while
            }catch(IOException ioException){
                ioException.printStackTrace();
            }
        }

        //wait for connection, display connection

        public void waitForConnection()throws IOException {
            showMessage("Waiting for connection...\n");
            connection = server.accept();
            showMessage("Now connected to " +connection.getInetAddress().getHostName());
        }

        //stream to send and receive info
        public void setupStreams()throws IOException{
            output = new ObjectOutputStream(connection.getOutputStream());
            output.flush();
            input = new ObjectInputStream(connection.getInputStream());
            showMessage("\n Connection fully established \n");

        }

        //during strand searching

        public void whileChatting()throws IOException {
            String message = "You are now connected";
            sendMessage(message);
            ableToType(true);

            do {
                //send and receive info

                try {
                    message = (String) input.readObject();
                    showMessage("\n" +message);
                }catch(ClassNotFoundException classNotFoundException) {
                    showMessage("\nUser info is invalid..");
                }
            }while(!message.equals("CLIENT - END"));
        }

        //close all streams and sockets
        public void closeEverything() {
            showMessage("\n Closing connection..\n");
            ableToType(false);
            try {
                output.close();
                input.close();
                connection.close();
            }catch(IOException ioException) {
                ioException.printStackTrace();
            }
        }

        //send message to client
        public void sendMessage(String message) {
            try {
                output.writeObject("SERVER - "+  message);
                output.writeObject("SERVER - "+ count);                                             //output dna result here
                output.flush();
                showMessage("\n SERVER - "+message);//shows history of user input....might not need
            }catch(IOException ioException){
                chatWindow.append("\n Your message is invalid");
            }
        }

        //update chat window
        public void showMessage(final String text) {
            SwingUtilities.invokeLater(
                new Runnable() {
                    public void run() {
                        chatWindow.append(text);
                    }
                }
                    );      

            }//end showMessage

        //let the user type

        public void ableToType(final boolean tof) {
            SwingUtilities.invokeLater(
                new Runnable() {
                    public void run() {
                        userText.setEditable(tof);
                    }
                }
                    );  
        }
}


Класс поиска генома

public class GenomeSearcher {

    //read from file
    public void readFile()throws Exception {
    Server s = new Server();
    File chromosome = new File("chr1.fa");

    BufferedReader br = new BufferedReader(new FileReader (chromosome));

    StringBuilder sb = new StringBuilder();
    String st;
    while((st = br.readLine()) != null) {
        sb.append(st);
    }//end while


    //time to count how many times a sequence appears


    }


    public int countSequence(String findSequence, String chromosome) {
        int count = 0;
        String result;

        List<Integer> Search = new ArrayList<Integer>();
        List<String> searchOutput = new ArrayList<String>();
        Server s = new Server();

        try {
            FileInputStream fstream = new FileInputStream(chromosome);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader (in));
            String strLine;

            while((strLine = br.readLine()) != null) {
                int startIndex = strLine.indexOf(findSequence);
                while (startIndex != -1){
                    count++;
                    startIndex = chromosome.indexOf(findSequence, startIndex +findSequence.length());
                }
            }
            in.close();

        }catch(Exception e) {
        s.showMessage("Nothing");
        }

        //Search.add(count);

    //  String result = Integer.toString(count);

        for(Integer i: Search) {
            searchOutput.add(String.valueOf(i));
        }

        StringBuffer sb = new StringBuffer();

        for(String sw: searchOutput) {
            sb.append(sw);
            sb.append(" ");
        }

        String str;
        str = sb.toString(); 

        s.showMessage(str);

        for (String sp : searchOutput)
          {               
               System.out.println(sp);      
          }

        System.out.println(count);
        return count;
    }   



}


1 Ответ

0 голосов
/ 19 апреля 2020

Вы можете записать данные в OutputStream и прочитать их из InputStream.

Если вы хотите отправить данные с клиента на сервер, клиент должен записать их в OutputStream чтобы сервер мог прочитать его из InputStream.

Если сервер должен что-то отправить клиенту, сервер должен записать в OutputStream, чтобы клиент мог прочитать его из InputStream. Если вам нужно и то и другое, оба должны писать и читать (читать и писать на другой стороне).

Если вы хотите отправить ArrayList сериализуемых объектов (String s сериализуемы) с клиента на сервер, вы можете просто написать его (на стороне клиента), используя output.writeObject(theArrayList); и получить его (на стороне сервера), используя ArrayList<String> theList=(ArrayList<String>)input.readObject(); (как вы используете потоки объектов.

Если вы хотите передавать необъектные данные (например, int s), вы можете использовать другие методы read и write, которые предоставляют потоки.

Но если и сервер, и клиент читают одновременно, и никто не написал ничего, что еще не было прочитано, вы получите Deadlock. Это означает, что оба процесса ждут друг друга и не проснутся, поскольку им нужен другой процесс (который спит), чтобы заставить их проснуться .

...