【问题标题】:How to get input from server console in a client server program如何在客户端服务器程序中从服务器控制台获取输入
【发布时间】:2016-02-13 00:37:55
【问题描述】:

我已经使用 java(多线程)实现了一个客户界面。在客户端,客户在服务器已经运行时登录。多个客户端可以登录,为每个客户端创建一个线程。我想要实现的是当多个客户端登录时,我想在服务器控制台(eclipse)中输入一个命令,列出我在控制台上输入内容后登录的所有客户端。

客户端代码:

btnLogin.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                Connection conn = null;
                try // try block
                {
                    // declare variables
                    String username = "";
                    String pwd = "";

                    // get values using getText() method
                    username = loginEmail.getText().trim();
                    pwd = new String(loginPassword.getPassword());

                    // check condition it field equals to blank throw error
                    // message
                    if (username.equals("") || pwd.equals("")) {
                        JOptionPane.showMessageDialog(null, " name or password or Role is wrong", "Error",
                                JOptionPane.ERROR_MESSAGE);
                    } else // else insert query is run properly
                    {
                        String IQuery = "select accountnumber, customername, address from `customeraccount` where emailaddress=? and password=?";
                        String accnum = null;
                        System.out.println("Connecting to a selected database...");

                        // STEP 3: Open a connection
                        conn = DriverManager.getConnection(DB_URL, user_name, password);
                        System.out.println("Connected database successfully...");
                        PreparedStatement stmt = conn.prepareStatement(IQuery);
                        stmt.setString(1, username);
                        stmt.setString(2, pwd);
                        ResultSet rs = stmt.executeQuery();
                        while (rs.next()) {
                            detailName.setText(rs.getString("customername"));
                            detailAddress.setText(rs.getString("address"));
                            accnum = rs.getString("accountnumber");
                        }
                        out.println(accnum);
                        out.println(detailName.getText());
                        rs.close();
                        ((java.sql.Connection) conn).close();
                    }
                } catch (SQLException se) {
                    // handle errors for JDBC

                    se.printStackTrace();
                } catch (Exception a) // catch block
                {
                    a.printStackTrace();
                }
            }
        });

服务器端代码:

public class StoreServer {
static ArrayList<String[]> list2 = new ArrayList<String[]>();

public static void main(String[] args) throws IOException {
    System.out.println("The server is running.");
    int clientNumber = 0;
    ServerSocket listener = new ServerSocket(3355);

    try {
        while (true) {
            new Thread(new Customer(listener.accept(), clientNumber++)).start();
        }
    } finally {
        listener.close();
    }
}

private static class Customer implements Runnable {
    private Socket socket;
    private int clientNumber;

    public Customer(Socket socket, int clientNumber) {
        this.socket = socket;
        this.clientNumber = clientNumber;
        // log("New connection with client# " + clientNumber + " at " +
        // socket);
    }

    /**
     * Services this thread's client by first sending the client a welcome
     * message then repeatedly reading strings and sending back the
     * capitalized version of the string.
     */
    public void run() {
        try {

            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);


            while (true) {

                    System.out.println("Account Number: " + acnum + "  Name: " + name);
                if (acnum == null || acnum.equals(".")) {
                    break;
                }
                // out.println(input.toUpperCase());
            }
        } catch (IOException e) {
            log("Error handling client# " + clientNumber + ": " + e);
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                log("Couldn't close a socket, what's going on?");
            }
            // log("Connection with client# " + clientNumber + " closed");
        }
    }}}

【问题讨论】:

    标签: java mysql sockets client-server serversocket


    【解决方案1】:

    这是你想要的sn-p:

    private static class CommandListener implements Runnable {
    
        @Override
        public void run() {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            while(true) {
                try {
                    String command = br.readLine();
                    if(command.equals("listClients")) {
    
                        // Assuming you will have static list of customer. In which you will 
                        // add a customer/client when a new client get connected and remove 
                        // when a client get disconnected 
    
                        System.out.println("Total Connected customer :" + customers.size());
                        System.out.println("Details :");
                        for(Customer cust : customers) {
                            System.out.println(cust.getName());
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    在您的StoreServer 类中创建CommandListener 类的对象,并在监听服务器端口之前将其传递给线程。像这样的:

    public class StoreServer {
    
        static ArrayList<String[]> list2 = new ArrayList<String[]>();
        static List<Customer> customers = new LinkedList<Customer>();
    
        public static void main(String[] args) throws IOException {
            System.out.println("The server is running.");
            int clientNumber = 0;
            ServerSocket listener = new ServerSocket(3355);
            Thread commandListenerThread = new Thread(new CommandListener());
            commandListenerThread.start();
            try {
                while (true) {
                    Socket socket = listener.accept();
                    Customer cust = new Customer(socket, clientNumber++);
                    customers.add(cust);
                    new Thread(cust).start();
                }
            } finally {
                listener.close();
            }
        .....
    

    请注意,这只是一个 sn-p,而不是适当的优化代码。除此之外,可以在您发布的代码中进行很多改进,例如保持线程创建逻辑的阈值等。但我跳过了这一点,因为您的问题仅与从 @987654325 中的控制台获取输入有关@ 程序。

    【讨论】:

    • 我认为这是最合适的答案。谢谢苏米特。
    【解决方案2】:

    在开始监听传入的套接字之前,您应该启动一个新线程。在这个线程中,您可以从 System.in 中读取行。 (用 InputStreamReader 包装 System.in,然后用 BufferedReader 包装)。现在,当您从控制台读取某个命令时,您可以打印出有关已连接客户端的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2021-11-07
      • 1970-01-01
      相关资源
      最近更新 更多