I implemented a client interface using java (multithreading). The client on the client side is registered when the server is already running. Multiple clients can log in, creating a stream for each client. What I want to achieve is when several clients register. I want to enter a command in the server console (eclipse), which lists all registered users after entering anything on the console.
ClientSide Code:
btnLogin.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Connection conn = null;
try
{
String username = "";
String pwd = "";
username = loginEmail.getText().trim();
pwd = new String(loginPassword.getPassword());
if (username.equals("") || pwd.equals("")) {
JOptionPane.showMessageDialog(null, " name or password or Role is wrong", "Error",
JOptionPane.ERROR_MESSAGE);
} else
{
String IQuery = "select accountnumber, customername, address from `customeraccount` where emailaddress=? and password=?";
String accnum = null;
System.out.println("Connecting to a selected database...");
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) {
se.printStackTrace();
} catch (Exception a)
{
a.printStackTrace();
}
}
});
Server side of the code:
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;
}
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;
}
}
} catch (IOException e) {
log("Error handling client# " + clientNumber + ": " + e);
} finally {
try {
socket.close();
} catch (IOException e) {
log("Couldn't close a socket, what going on?");
}
}
}}}
source
share