Java Socket实时从套接字读取

时间:2010-12-14 14:22:18

标签: sockets ssh

我正在编写一个java applet来模拟与ubuntu机器的ssh连接,我设置连接,执行命令,然后回复响应,一切看起来都很好。 但是,我在这里有一个小问题,我想实时接收服务器套接字响应,所以我可以在Applet上实时模拟,但似乎我在命令执行完成时收到响应。  例如,我有一个测试tcl文件,我让执行在每个语句之间睡5秒钟,我应该每5秒响应一次applet,而不是我最终得到所有的响应。 有什么想法吗?

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ssh_applet.java
 *
 * Created on 9-Dec-2010, 11:10:06 AM
 */

/**
 *
 * @author xzhang
 */
//import javax.swing.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import javax.swing.*;

public class ssh_applet extends javax.swing.JApplet{
    private String host_name = null;
    private String user_name = null;
    private String pass_word = null;
    private Connection app_conn;
    private Session app_session;
    /** Initializes the applet ssh_applet */
    public void init() {
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /** This method is called from within the init() method to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        ssh_input = new javax.swing.JPanel();
        connect = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        hostname = new javax.swing.JTextField();
        username = new javax.swing.JTextField();
        password = new javax.swing.JPasswordField();
        ssh_command = new javax.swing.JTextField();
        ssh_output_pannel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        ssh_output = new javax.swing.JTextArea();
        clear_text = new javax.swing.JButton();

        connect.setText("Connect");
        connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectActionPerformed(evt);
            }
        });

        jLabel1.setText("Host Name");

        jLabel2.setText("User Name");

        jLabel3.setText("Password");

        hostname.setText("10.4.0.135");

        username.setText("xzhang");

        password.setText("Samboapple0827!");

        ssh_command.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ssh_commandActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ssh_inputLayout = new javax.swing.GroupLayout(ssh_input);
        ssh_input.setLayout(ssh_inputLayout);
        ssh_inputLayout.setHorizontalGroup(
            ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_inputLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(username, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(password)
                            .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(connect))
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addGap(49, 49, 49)
                        .addComponent(ssh_command, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(60, Short.MAX_VALUE))
        );
        ssh_inputLayout.setVerticalGroup(
            ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_inputLayout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(connect))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ssh_command, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        ssh_output.setColumns(20);
        ssh_output.setEditable(false);
        ssh_output.setLineWrap(true);
        ssh_output.setRows(5);
        jScrollPane1.setViewportView(ssh_output);

        clear_text.setText("Clear");
        clear_text.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clear_textActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ssh_output_pannelLayout = new javax.swing.GroupLayout(ssh_output_pannel);
        ssh_output_pannel.setLayout(ssh_output_pannelLayout);
        ssh_output_pannelLayout.setHorizontalGroup(
            ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_output_pannelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
                    .addComponent(clear_text, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        ssh_output_pannelLayout.setVerticalGroup(
            ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_output_pannelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(clear_text)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(ssh_input, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(ssh_output_pannel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(ssh_input, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ssh_output_pannel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>                        

    private void connectActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
                        /*get host_name*/
                    host_name=hostname.getText();
                    user_name=username.getText();
                    pass_word=password.getText();
            /* Create a connection instance */
                      app_conn=new Connection(host_name);
                      try
            {
                              app_conn.connect();
            /* Authenticate.
             * If you get an IOException saying something like
             * "Authentication method password not supported by the server at this stage."
             * then please check the FAQ.
             */
            boolean isAuthenticated = app_conn.authenticateWithPassword(user_name, pass_word);

            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");

                         JOptionPane.showMessageDialog(null, "You are connected to host "+host_name, "Connection",
                                        JOptionPane.INFORMATION_MESSAGE);
            /* Create a session */
                        }
                        catch(IOException e)
                        {}


    }                                       

    private void ssh_commandActionPerformed(java.awt.event.ActionEvent evt) {                                            
            // TODO add your handling code here:
        String command=ssh_command.getText();
         try
        {

        app_session=app_conn.openSession();
        app_session.execCommand( command );
            InputStream stdout = new StreamGobbler( app_session.getStdout() );
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            String line ;
            while( (line= br.readLine()) != null )
            {
                ssh_output.append( line + "\n" );
                //line = br.readLine();
            }
            // DEBUG: dump the exit code
            System.out.println( "ExitCode: " + app_session.getExitStatus() );

            // Close the session
            app_session.close();
        }
         catch(Exception e)
         {}
    }                                           

    private void clear_textActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        ssh_output.setText("");
    }                                          


    // Variables declaration - do not modify                     
    private javax.swing.JButton clear_text;
    private javax.swing.JButton connect;
    private javax.swing.JTextField hostname;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPasswordField password;
    private javax.swing.JTextField ssh_command;
    private javax.swing.JPanel ssh_input;
    private javax.swing.JTextArea ssh_output;
    private javax.swing.JPanel ssh_output_pannel;
    private javax.swing.JTextField username;
    // End of variables declaration                   

}

这是我的代码,我正在使用ganymed-ssh2库,无法获取冲洗的地方

4 个答案:

答案 0 :(得分:1)

每当服务器从程序中获取一些输出时,它应该将其推出网络并刷新流。

答案 1 :(得分:0)

没有任何代码可以查看,很难提供帮助。但是,听起来缓冲区需要刷新。

答案 2 :(得分:0)

您可能需要刷新套接字上的输出。看看Java Flush Socket。 在您的代码中,您可以在输出上调用flush()以强制它读取数据。

答案 3 :(得分:0)

弄清楚readline将阻止来自服务器的所有输入,更改为读取字节,它的工作原理。现在唯一的事情是考虑用户一个线程将文本追加到textarea。谢谢你们。