簡體   English   中英

為什么我的數據在界面上顯示的方式有所不同?

[英]Why is my data being displayed differently on my interface?

作為分配問題的一部分,我必須創建一個涉及客戶端和服務器的應用程序。 客戶端允許用戶連接到數據庫,並在連接時從組合框中選擇ID號,並從數據庫中調用相關信息。 信息首先存儲在數組中,然后顯示在相關的文本字段中。 盡管我確實知道這樣的數組是不合邏輯的,但這是分配的要求,所以我不得不使用它。 服務器將在啟動時顯示並且客戶端已連接。 客戶端界面將從服務器接收類似的響應並顯示它。 當用戶選擇“發送到服務器”時,它將在服務器以及客戶端界面上發送並顯示信息。 下圖顯示了它是如何工作的以及錯誤是什么:

當用戶連接時,人的信息將顯示在文本字段中: 在此處輸入圖片說明

當用戶單擊“發送到服務器時,信息將同時在客戶端和服務器界面上顯示,如下所示(這是必須的工作方式): 在此處輸入圖片說明

在客戶端界面上選擇下一個人時,將顯示以下信息: 在此處輸入圖片說明

但是,當我選擇“發送到服務器”時,它將在服務器界面上正確顯示詳細信息,但在客戶端界面上顯示的只是用戶已連接到服務器,客戶端編號和日期,如下所示: 在此處輸入圖片說明

但是,當我與第三方進行相同的處理時,它將在服務器上顯示當前人員的詳細信息,並在客戶端界面上顯示先前人員的詳細信息,如下所示: 在此處輸入圖片說明

我已經完成了兩個接口的全部編碼,但是找不到問題(基於我的編碼知識)。 因此,我的問題是導致該問題的原因是什么,我在屏幕截圖中已演示了該如何解決?

這是服務器類中的套接字編碼(其余只是GUI編碼):

try
        {
            //creates the server socket
            ServerSocket ssocket = new ServerSocket(8100);

            while(true)
            {
                //accepts the socket connection
                Socket ssocket2 = ssocket.accept();
                //increments the client number
                clientNum++;
                //creates the task class
                ProcessClients pc = new ProcessClients(ssocket2,clientNum);
                Thread thread = new Thread(pc);
                //starts the thread
                thread.start();
            }
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(null, "There was a problem connecting to the server", "SERVER ERROR", JOptionPane.ERROR_MESSAGE);
        }

這是服務器接口中ProcessClients類的編碼:

class ProcessClients implements Runnable
{
    //declares the socket
    private Socket s;
    //declares the client number
    private int clientNumber;
    //declares the array for the User object
    ArrayList<User> array = new ArrayList<>();

    //constructor
    public ProcessClients(Socket soc, int clientNum)
    {
        this.s = soc;
        clientNumber = clientNum;

    }

    @Override
    public void run()
    {
        try
        {
            //declares DataInputStream for retrieving data
            DataInputStream dis = new DataInputStream(s.getInputStream()); 
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());            
            //message to be displayed showing client number and date of connection
            String connected = "\nConnected to Client Number: " + clientNumber + "\nConnection Date: " + new Date();
            jtaResults.append(connected);
            while(true)
            {
                //message from the server responding to connection with client number, time and date
                String response = "\nSERVER RESPONSE:\nConnected to server:\nClient Number: " + clientNumber + "\nConnection Date: " + new Date(); 
                dos.writeUTF(response);
                //input stream for the userID
                int userID = dis.readInt();
                //input stream for the lastName
                String lastName = dis.readUTF();
                //input stream for the firstName
                String firstName = dis.readUTF();
                //input stream for the age
                int age = dis.readInt();
                //creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age);
                //add object to array list
                array.add(use);
                //confirmation message regarding data received from client
                String confirm = "\n SERVER RESPONSE:\nData received from client number: " + clientNumber +
                        "\nUser ID: " + userID + "\nFirst Name: " + firstName + "\nLast Name: " + lastName + 
                        "\nAge: " + age + "\nDate received: " + new Date();
                dos.writeUTF(confirm);
                //displays the client number in the text area
                jtaResults.append("\n\n Message from client number: " + clientNumber + "\n");
                //displays the user ID in the text area
                jtaResults.append("User ID: " + use.getuserID() + "\n");
                //displays the first name in the text area
                jtaResults.append("First Name: " + use.getfirstName() + "\n");
                //displays the last name in the text area
                jtaResults.append("Last Name: " + use.getlastName() + "\n");
                //displays the age in the text area
                jtaResults.append("Age: " + use.getage());
                jtaResults.append("\nDate received: " + new Date());
            }
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, "There was a problem retrieving the data", "SERVER ERROR", JOptionPane.ERROR_MESSAGE);
        } 
    }

這是客戶端類的編碼(不包括GUI編碼):

public ClientApp()
    {
        InterfaceProperties();
        try
        {
            Socket csocket = new Socket("localhost", 8100);
            input = new DataInputStream(csocket.getInputStream());
            output = new DataOutputStream(csocket.getOutputStream());
            String sresponse = input.readUTF();
            jtaResults.append(sresponse);
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, "There was a problem connecting to the server", "SERVER ERROR", JOptionPane.ERROR_MESSAGE);
        }
    }

    //method for connecting to the database
        private void ConnectDB()
        {
            String query = "Select * from studentinfo";
            try
            {
                Class.forName("com.mysql.jdbc.Driver");
               //connection
                Connection conn = (Connection)
                        //root and username and password for access to the database
                DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb","root","");

                //create the statement that will be used
                Statement stmt=conn.createStatement();
                ResultSet rs = stmt.executeQuery(query);
                while(rs.next())
                {
                    int userID = rs.getInt("userID");
                    cboIDNums.addItem(userID);

                }
            }
            catch(Exception e)
            {
                JOptionPane.showMessageDialog(null, "An error occured while trying to connect to the database", "CONNECTION ERROR!", JOptionPane.ERROR_MESSAGE);
            }

        }

        public int idValue;

        private void searchDB(int ID)
        {
            try
            {
                idValue = ID;
                Class.forName("com.mysql.jdbc.Driver");
               //connection
                Connection conn = (Connection)
                        //root and username and password for access to the database
                DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb","root","");

                //create the statement that will be used
                PreparedStatement stmt=conn.prepareStatement("Select * from studentinfo where userID = '" + ID + "'");

                ResultSet rs = stmt.executeQuery();
                java.sql.ResultSetMetaData rsmd = rs.getMetaData();
                int numColumns = rsmd.getColumnCount();

                rs.first();
                int rowcount = 0;
                do
                {
                    rowcount++;
                } 
                while (rs.next());

                rs.first();
                int rowindex = 0;
                Object array2D[][] = new Object[rowcount][];
                do 
                {
                    array2D[rowindex] = new Object[numColumns];
                    for (int i = 0; i < numColumns; i++) 
                    {
                        array2D[rowindex][i] = rs.getObject(i + 1);
                    }


                    rowindex++;
                } 
                while (rs.next());
                jtfLastName.setText(array2D[0][2].toString());
                jtfFirstName.setText(array2D[0][1].toString());
                jtfAge.setText(array2D[0][3].toString());


            }
            catch(Exception e)
            {
                JOptionPane.showMessageDialog(null, "There was a problem retrieving data", "SERVER ERROR", JOptionPane.ERROR_MESSAGE);
            }
        }

        //declarng a click function
        boolean clicked = true;

        //method for the action listener
        private void btnConnectOptionActionPerformed(java.awt.event.ActionEvent evt)
        {
            if(clicked)
            {
                //changes the butten text from 'Connect' to 'Disconnect'
                btnConnectOption.setText("Disconnect");
                clicked = false;
                ConnectDB();
            }
            else
            {
                //changes the button text from 'Disconnect' to 'Connect'
                btnConnectOption.setText("Connect");
                clicked = true;

                //resets the text fields
                jtfAge.setText("");
                jtfFirstName.setText("");
                jtfLastName.setText("");
                //resets the combo box
                cboIDNums.removeAllItems();
                try
                {
                    Class.forName("com.mysql.jdbc.Driver");
               //connection
                Connection conn = (Connection)
                        //root and username and password for access to the database
                DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb","root","");
                //closes the database connection
                conn.close();
                }
                catch(Exception e)
                {
                    JOptionPane.showMessageDialog(null, "The database does not want to disconnect", "DISCONNECTION ERROR", JOptionPane.ERROR_MESSAGE);
                }
            }
        }

        //method for the action listener
        private void btnSendToServerActionPerformed(java.awt.event.ActionEvent evt)
        {
            try
            {
                int userIDs = Integer.parseInt(cboIDNums.getSelectedItem().toString());
                String lastNames = jtfLastName.getText();
                String firstNames = jtfFirstName.getText();            
                int ages = Integer.parseInt(jtfAge.getText());

                output.writeInt(userIDs);
                output.writeUTF(lastNames);
                output.writeUTF(firstNames);
                output.writeInt(ages);
                output.flush();
                jtfFirstName.setText("");
                jtfLastName.setText("");
                jtfAge.setText("");
                String receive =  input.readUTF();
                jtaResults.append(receive);
            }
            catch(Exception ex)
            {
                JOptionPane.showMessageDialog(null, "An error occured loading data from text fields!\nFields empty!", "ERROR!", JOptionPane.ERROR_MESSAGE);
            }
        }

        private void cboIDNumsActionPerformed(java.awt.event.ActionEvent evt)
        {
            try
            {
                idValue = Integer.parseInt(cboIDNums.getSelectedItem().toString());
                searchDB(idValue);
            }
            catch(Exception e)
            {
                JOptionPane.showMessageDialog(null, "Database disconnected", "DISCONNECT SUCCESSFUL", JOptionPane.PLAIN_MESSAGE);
            }
        }

對我來說,它具有緩沖沖洗效果。 嘗試在ProcessClients.run方法中對dos.write*的最后一次調用之后添加dos.flush()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM