这是我的服务器代码。我有一个全局ArrayList变量(用户),当用户登录时,它将推送到“用户”,然后将其发送给所有连接的客户端。
问题:我在发送“用户”之前先对其进行了检查,但是当客户端收到该消息时,“用户”不会更新。另外,当新客户端连接到服务器时,它将获得更新的“用户”。谢谢
加:使用ArrayList的情况我使用修改过的String,客户端已更新
public class ServerController {
private ServerSocket server;
private int port = ServerConfig.getInstance().PORT;
private HashSet<ObjectOutputStream> players = new HashSet<ObjectOutputStream>();
private volatile ArrayList<User> users = new ArrayList<User>();
//open connection and do a few stuffs
private class Handler extends Thread {
private ObjectOutputStream oos;
private ObjectInputStream ois;
private Socket client;
public Handler(Socket s) {
client = s;
}
public void listening() {
try {
ois = new ObjectInputStream(client.getInputStream());
oos = new ObjectOutputStream(client.getOutputStream());
players.add(oos);
for (;;) {
//receive packet from client and navigate
}
}
//Client wants to Sign In
private void handleSignIn(DataPackage dp) {
System.out.println("sign in");
User u = (User)dp.getData();
try {
DataPackage re = LoginController.getInstance().getUserDAO(u);
if (re != null) {
oos.writeObject(re);
addUser(u);
handleUpdateTable();
}
else {
oos.writeObject(new DataPackage(null, ActionType.SIGN_IN));
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
//updating table when someone change
private void handleUpdateTable() {
System.out.println("update table");
System.out.println(users.size());
try {
DataPackage dp = new DataPackage(users, ActionType.UPDATE);
for (ObjectOutputStream oos : players)
oos.writeObject(dp);
} catch (IOException ex) {
System.err.println(ex);
}
}
//removing signed out user from users
private void handleSignOut(DataPackage dp) {
User u = (User)dp.getData();
removeUser(u.getUsername());
handleUpdateTable();
}
@Override
public void run() {
listening();
}
private void addUser(User u) {
synchronized (users) {
users.add(u);
}
}
private void removeUser(String username) {
Iterator<User> iter = users.iterator();
while (iter.hasNext()) {
User u = iter.next();
if (u.getUsername().equals(username))
iter.remove();
}
}
}
}