我使用Java开发了一个客户端/服务器聊天应用程序,我想知道如何从数组中删除用户。客户端登录时,用户名保存在"username array"中,客户端ID保存在"client array"中。为了允许服务器接受多个客户机,我使用线程。现在有谁可以指导我如何从数组中删除用户,并关闭该用户的连接。
添加新客户端并将ID保存在客户端数组
public class AddClient implements Runnable {
Thread t;
AddClient(String tot) {
t = new Thread(this, tot);
t.start();
}
public void run() {
while (true) {
try {
try {
waitClient();
} catch (Exception ex) {
ex.printStackTrace();
}
for (int i = 0; i < client.length; i++) {
if (client[i] == 0) {
client[i] = i + 1;
id = i;
break;
}
}
//set stream to send and receive data
out[client[id]] = new ObjectOutputStream(connect.getOutputStream());
out[client[id]].flush();
in[client[id]] = new ObjectInputStream(connect.getInputStream());
用户名保存在用户名数组
username[client[id]] = cm.sender; //Add user in username[] array
删除用户
public synchronized void removeUser(int number) {
int position = number;
System.out.println("Server removing user " + username[number] + "which is client " + number);
for (int i = 0; i <= client.length; i++) {
if (position == client[i]) {
System.out.println("User to be remove found");
try {
client[i + 1] = client[i];
in[position].close();
out[position].close();
username[position] = null;
position = position - 1;
} catch (Exception e) {
e.printStackTrace();
}
}
}
我正在尝试使用HashTable来添加和删除客户端
public class ChatServerProtocol {
private String nick;
private AddClient a;
private Hashtable<String, AddClient> nicks = new Hashtable<String, AddClient>();
private boolean add_nick(String nick, AddClient a) {
if (nicks.containsKey(nick)) {
return false;
} else {
nicks.put(nick, a);
return true;
}
}
private boolean remove_nick(String nick, AddClient a) {
if (!(nicks.containsKey(nick))) {
return false;
} else {
nicks.remove(nick);
return true;
}
}
public ChatServerProtocol(AddClient a) throws IOException {
nick = null;
a = a;
}
现在我如何调用add_nick方法。每当客户端登录时,将用户名发送到服务器,服务器将其读取为cm.sender。我还需要包括线程变量。所以如何添加用户名,以便以后我可以删除它。
ChatServerProtocol.add_nick(cm.sender);
不,保存在数据库中将不是一个好主意。记住,您只保存会话长度的详细信息,数据库的基本概念是在会话结束后使用它。如果你的会话被中断,因为网络问题等?
使用Map代替普通数组,使用key作为客户端ID, value作为用户名。删除用户名将是一个普通的调用,如map.remove(clientID);
EDIT AS YOU ASKED:请注意,这段代码是不完整的,只是你给的。
AddClient实现Runnable {线程t;
private Map<int, String> users = new HashMap <int, String>();
AddClient(String tot) {
t = new Thread(this, tot);
t.start();
}
public void run() {
while (true) {
try {
try {
waitClient();
} catch (Exception ex) {
ex.printStackTrace();
}
int clientId = users.size() + 1;
users.put(clientId, cm.sender);
//set stream to send and receive data
out[clientId] = new ObjectOutputStream(connect.getOutputStream());
out[clientId].flush();
in[clientId] = new ObjectInputStream(connect.getInputStream());
REMOVE USER METHOD
public synchronized void removeUser(int number) {
if(users.containsKey(number)) {
System.out.println("Server removing user " + users.get(number) + "which is client " + number);
users.remove(number);
} else {
System.out.println("User not in session");
}
}