作爲一個分配問題的一部分,我不得不創建一個涉及客戶端和服務器的應用程序。客戶端允許用戶連接到數據庫,並在連接時從組合框中選擇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);
}
}
我剛剛嘗試了您的建議,但沒有解決問題。 – Osiris93